既然你在這兩個查詢mr.id
分組,我假設你想要的結果是這樣的:
mr.id | labor_cnt | mtrial_cnt
--------------------------------
1 | 5 | 3
2 | null | 6
3 | 4 | 2
4 | 3 | null
...
如果這就是你要找的內容,那麼你就可以結合使用公用表表達式查詢。喜歡的東西:
WITH labor as (
SELECT mr.id AS mrid, count(ml.id) AS labor_cnt
FROM mreq mr JOIN mlbr ml ON mr.id = ml.mrid
WHERE mr.id IN (1235, 3355)
GROUP BY mr.id),
mtrial as (
SELECT mr.id AS mrid, count(mm.id) AS mtrial_cnt
FROM mreq mr JOIN mmrm mm ON mr.id = mm.mrid
WHERE mr.id in (1235, 3355)
GROUP BY mr.id)
SELECT COALESCE(l.mrid, m.mrid), l.labor_cnt, m.labor_cnt
FROM labor l FULL OUTER JOIN mtrial m ON mrid
ORDER BY mrid;
編輯補充
它看起來像你使用MySQL,以及MySQL不支持公共表表達式。 MySQL支持子查詢,所以這可能會起作用(注意:我沒有驗證語法,因爲我沒有可用的MySQL實例):
SELECT COALESCE(l.mrid, m.mrid), l.labor_cnt, m.labor_cnt
FROM
(SELECT mr.id AS mrid, count(ml.id) AS labor_cnt
FROM mreq mr JOIN mlbr ml ON mr.id = ml.mrid
WHERE mr.id IN (1235, 3355)
GROUP BY mr.id) AS labor
FULL OUTER JOIN
(SELECT mr.id AS mrid, count(mm.id) AS mtrial_cnt
FROM mreq mr JOIN mmrm mm ON mr.id = mm.mrid
WHERE mr.id in (1235, 3355)
GROUP BY mr.id) AS mtrial
ON mrid
ORDER BY mrid;
你叫什麼結合?..結果如何查找這兩個查詢? –