2016-06-18 62 views
0

我有2個查詢。 查詢1: -在postgres中合併多個查詢

select mr.id,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 

查詢2: -

select mr.id,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 

嘗試使用UNION ALL,但將無法正常工作。建議任何替代方法來合併它們。

+0

你叫什麼結合?..結果如何查找這兩個查詢? –

回答

1

既然你在這兩個查詢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; 
+0

是的,我喜歡這種想法。可能適合我!謝謝。 –

+0

獲取#1064 - 您的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在第一行使用'labor as(SELECT mr.id AS mrid,count(ml.id)AS labor_cnt FROM'附近的正確語法' –

+0

'您將此標籤標記爲'postgresql',所以我使用了postgres的語法,我不確定mysql的等效語法是什麼, – jmelesky