在 postgres 中组合多个查询
Combine multiple queries in postgres
我有 2 个问题。
查询 1:-
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 但行不通。建议将它们结合起来的任何替代方法。
由于您在两个查询中都按 mr.id
分组,我假设您想要的结果类似于:
mr.id | labor_cnt | mtrial_cnt
--------------------------------
1 | 5 | 3
2 | null | 6
3 | 4 | 2
4 | 3 | null
...
如果这正是您要查找的内容,那么您可以将查询与常见的 table 表达式结合起来。类似于:
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 不支持常见的 table 表达式。 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;
我有 2 个问题。 查询 1:-
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 但行不通。建议将它们结合起来的任何替代方法。
由于您在两个查询中都按 mr.id
分组,我假设您想要的结果类似于:
mr.id | labor_cnt | mtrial_cnt
--------------------------------
1 | 5 | 3
2 | null | 6
3 | 4 | 2
4 | 3 | null
...
如果这正是您要查找的内容,那么您可以将查询与常见的 table 表达式结合起来。类似于:
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 不支持常见的 table 表达式。 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;