我正在尝试创建一个始终显示表的所有行的查询,但如果 where 子句不匹配,则为 a 列提供默认值。
我有一个与房屋表具有 N 对 N 关系的服务表。在中间表中,我有以下列 idHouse、idService、active。
例如我有这个:
服务:
id, name
1, a
2, b
3, c
4, d
房子:
id
1
2
房子有服务:
idService, idHouse, active
1, 1, 1
1, 2, 1
4, 2, 1
我尝试过子查询和所有类型的联接,但无法解决该问题。这是我的第一次尝试。
select
s.idService id, s.name name, IFNULL(v.active, 0) active
from house_has_service v
right join service s on s.id = v.idService
where
v.idHouse is null or v.idHouse = (houseId)
order by s.id
(houseId) is the variable I pass
我想要的结果应该是这样的:
房屋ID = 1
id, name, active
1, a, 1
2, b, 0
3, c, 0
4, d, 0
房屋ID=2
id, name, active
1, a, 1
2, b, 0
3, c, 0
4, d, 1
房屋ID=3
id, name, active
1, a, 0
2, b, 0
3, c, 0
4, d, 0
最佳答案
SELECT s.id,
s.name,
COALESCE(hhs.active, 0) AS active
FROM service s
LEFT JOIN house_has_service hhs
ON s.id = hhs.idService
AND hhs.idHouse = @houseID
ORDER BY s.id;
关于mysql - 如果 where 语句不匹配,如何显示表的所有行但具有默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54579069/