我的查询中有错误,我想要一些帮助。我有三张桌子
**每个房间可以有不止一个女人或男人。
我想算一下,有多少女性和男性在(1,2,3),状态=' ADULT',类型=' LUX'和active = 1。因此我需要这样的结果:
+----+--------+-----------+----------+------------+
| id | number | name | CountMen | CountWomen |
+----+--------+-----------+----------+------------+
| 1 | 23 | 1st suite | 2 | 4 |
| 3 | 4 | 2nd suite | 1 | 2 |
+----+--------+-----------+----------+------------+
SELECT id,number,name,
sum(case when Men.status='ADULT' then 1 else 0 end) as CountMen,
sum(case when Women.status='ADULT' then 1 else 0 end) as CountWomen
FROM Rooms left join Men
on Rooms.id=Men.roomid
left join Women on Room.id=Women.roomid where
(type='LUX') and (active=true) and (id in (1,2,3))
group by id;
问题是我在计数器中有时会得到错误的结果。
答案 0 :(得分:1)
在left join
中, second 表中的条件必须位于on
子句中。如果您在查询中限定所有列名称,将会有所帮助。
但问题是因为您在性别表之间获得了笛卡尔积。这绝对是性别隔离不是好事的情况。你应该只有一个人表(这甚至不会引起定义二进制性别的其他问题)。
SELECT r.id, r.number, r.name,
(SELECT COUNT(*)
FROM men m
WHERE m.status = 'ADULT' AND r.id = m.roomid
) as CountMen,
(SELECT COUNT(*)
FROM women w
WHERE w.status = 'ADULT' AND r.id = w.roomid
) as CountWomen
FROM Rooms r
WHERE r.type = 'LUX' AND r.active = true AND r.id IN (1, 2, 3);
但是,您应该修复数据模型,以便人而不是隔离的性别表。