我有 2 个选择查询,我想将它们合并成一个不重复的查询。另外,我想使用所有表中找到的 shiftindex 主键加入它们。我该怎么做?
第一个选择语句是:
SELECT dbo.hist_exproot.year,
dbo.hist_exproot.[month#],
dbo.hist_exproot.month,
dbo.hist_exproot.day,
dbo.hist_exproot.[shift#],
dbo.hist_exproot.shift,
dbo.hist_loads.excav,
SUM(dbo.hist_loads.loadtons) AS 'TONS',
SUM(dbo.hist_loads.ex_tmcat00)/3600 AS 'TTOTAL',
SUM(dbo.hist_loads.ex_tmcat01+dbo.hist_loads.ex_tmcat02)/3600 AS 'T_EFECT'
FROM dbo.hist_exproot
INNER JOIN dbo.hist_loads
ON dbo.hist_exproot.shiftindex = dbo.hist_loads.shiftindex
WHERE (dbo.hist_exproot.year >= 16)
GROUP BY dbo.hist_exproot.year,
dbo.hist_exproot.[month#],
dbo.hist_exproot.month,
dbo.hist_exproot.day,
dbo.hist_exproot.[shift#],
dbo.hist_exproot.shift,
dbo.hist_loads.excav
第二个是:
SELECT dbo.hist_exproot.year,
dbo.hist_exproot.[month#],
dbo.hist_exproot.shiftdate,
dbo.hist_exproot.shift,
dbo.hist_statusevents.eqmt,
dbo.hist_exproot.crew,
dbo.hist_reasontable.category,
dbo.hist_statusevents.reason,
dbo.hist_reasontable.name,
dbo.hist_operlist.operid,
dbo.hist_statusevents.starttime,
dbo.hist_statusevents.endtime,
dbo.hist_statusevents.duration/3600 as 'Time',
dbo.hist_statusevents.comment
FROM dbo.hist_reasontable
INNER JOIN dbo.hist_statusevents
ON dbo.hist_reasontable.shiftindex = dbo.hist_statusevents.shiftindex
AND dbo.hist_reasontable.reason = dbo.hist_statusevents.reason
INNER JOIN dbo.hist_operlist
ON dbo.hist_statusevents.operid = dbo.hist_operlist.operid
AND dbo.hist_statusevents.shiftindex = dbo.hist_operlist.shiftindex
AND dbo.hist_reasontable.shiftindex = dbo.hist_operlist.shiftindex
INNER JOIN dbo.hist_exproot
ON dbo.hist_statusevents.shiftindex = dbo.hist_exproot.shiftindex
WHERE
(dbo.hist_exproot.year >= 16)
AND (dbo.hist_statusevents.unit = 2)
AND(dbo.hist_statusevents.eqmt <> 'L98')
AND (dbo.hist_statusevents.eqmt <> 'L96')
AND (dbo.hist_statusevents.eqmt <> 'L09')
AND (dbo.hist_statusevents.eqmt <> 'S47')
ORDER BY dbo.hist_exproot.shiftdate,
dbo.hist_statusevents.eqmt
如果您有疑问,请告诉我。
谢谢
最佳答案
实现您要求的最简单方法是:
SELECT DISTINCT *
FROM (Query 1) JOIN
(Query 2) ON...
这两个子查询的连接将由 on 后面的内容来处理,distinct 将消除所有重复项。
关于mysql - 连接 2 个不相等的 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640290/