在postgres中组合多个查询

时间:2016-06-18 14:57:42

标签: php postgresql php-pgsql

我有2个查询。 查询1: -

myvar = "value"

查询2: -

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

尝试使用联盟,但不会工作。建议任何替代方案来组合它们。

1 个答案:

答案 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;