您有一张表,您希望根据该表计算两个不同表中的项目数。在这个例子中,我使用了建筑物,男人和女人
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;
可能有别的方法吗?上述做法的问题是子查询中两个表的列是隐藏的,需要在外查询中重新声明。在两个单独的集合操作中执行此操作会产生不对称的情况。我们同样可以先加入女性,然后加入男性。