您有一个表,您希望计算两个不同表中的项目数。在这个例子中,我使用了建筑物,男人和女人
DROP TABLE IF EXISTS building;
DROP TABLE IF EXISTS men;
DROP TABLE IF EXISTS women;
CREATE TABLE building(name VARCHAR(255));
CREATE TABLE men(building VARCHAR(255), name VARCHAR(255));
CREATE TABLE women(building VARCHAR(255), name VARCHAR(255));
INSERT INTO building VALUES('building1');
INSERT INTO building VALUES('building2');
INSERT INTO building VALUES('building3');
INSERT INTO men VALUES('building1', 'andy');
INSERT INTO men VALUES('building1', 'barry');
INSERT INTO men VALUES('building2', 'calvin');
INSERT INTO men VALUES(null, 'dwain');
INSERT INTO women VALUES('building1', 'alice');
INSERT INTO women VALUES('building1', 'betty');
INSERT INTO women VALUES(null, 'casandra');
select
r1.building_name,
r1.men,
GROUP_CONCAT(women.name) as women,
COUNT(women.name) + r1.men_count as count
from
(select
building.name as building_name,
GROUP_CONCAT(men.name) as men,
COUNT(men.name) as men_count
from
building
left join
men on building.name=men.building
GROUP BY building.name) as r1
left join
women on r1.building_name=women.building
GROUP BY r1.building_name;
可能还有另一种方式吗?上述方法的问题是子查询中的两个表的列是隐藏的,需要在外部查询中重新声明。在两个单独的集合操作中执行此操作会创建不对称的情况。我们同样可以先与女性一起,然后是男性。
答案 0 :(得分:1)
在SQL Server中,我只会加入两个带有两个左连接的子查询 - 如果你正在寻找对称性:
SELECT *
FROM building
LEFT JOIN (SELECT building, etc. FROM men GROUP BY etc.) AS men_summary
ON building.name = men_summary.building_name
LEFT JOIN (SELECT building, etc. FROM women GROUP BY etc.) AS women_summary
ON building.name = women_summary.building_name
我倾向于使用首先声明的公共表表达式而不是子查询 - 它更具可读性(但不是ANSI - 但后来都不是GROUP_CONCAT
)。
答案 1 :(得分:1)
使用Union来合并男/女表中的数据
select building, [name] as menname, null as womenname from men
union
select building, null as menname, [name] as womenname from women
现在,您可以在子查询中添加一个“表”,您可以加入,计数或其他任何内容。
顺便说一下,我可以看出为什么Cas [s] andra在寒冷中出局,因为没有人相信她,但是dwain呢,他同样被众神诅咒了吗?