您好我有以下树表,我想实现名为“想要的结果”的表。 第一个是房子名称,第二个是每个房间的房间名称,第三个是每个房间的价格。 我想要一个房间的房间数。
TABLE_1
nid name
1 House 1
2 House 2
3 House 3
TABLE_2
Name house_ref_id id
Room1 1 20
Room1 2 21
Room1 2 22
Room1 3 23
Room1 3 24
TABLE_3
Price room_ref_id
0 20
100 21
150 22
0 23
120 24
通缉结果:
nid name Rooms w/ price
1 House1 0
2 House2 2
3 House3 1
我尝试了以下代码,但可以获得价格合适的房间
SELECT Name, COUNT(price) AS "rooms w/ price" FROM table_1
LEFT JOIN table_2 ON table_1.id = table_2.ref_id
LEFT JOIN table_3 ON table_2.room_ref_id = table_3.id
WHERE table_3.price>0
GROUP BY table_1.nid
但得到以下内容:
nid name rooms w/ price
1 nouse1 1
2 house2 2
3 house3 2
答案 0 :(得分:1)
关闭。 WHERE
中的条件将外连接转换为内连接。您需要将其移至ON
子句:
SELECT Name, COUNT(table3.id) AS "rooms w/ price"
FROM table_1 LEFT JOIN
table_2
ON table_1.id = table_2.ref_id LEFT JOIN
table_3
ON table_2.room_ref_id = table_3.id AND table_3.price > 0
GROUP BY table_1.nid;