我在想是否可以(如果可能的话,只使用一个查询)使查询返回默认值,如果行缺失?例如,考虑这两个表格,给定我的查询需要2个参数(place_id和user_id)。
T1
place_id / tag_id
1 2
1 3
1 4
2 4
3 2
4 5
T2
user_id / tag_id / count
100 2 1
100 3 20
200 4 30
200 2 2
300 5 22
如您所见,用户/标签(100,4)对缺失。我想要实现的是一条查询语句,能够返回这三个结果。
tag_id / count
2 1
3 20
4 0
我知道可以使用类似以下代码的方法实现,但这并不符合最终结果,因为它只在我预先知道 tag_id 时有效,并且只返回一行结果:
SELECT T1.tag_id, T2.count
from T1 t1
left join T2 t2 on t1.tagId=t2.tag_id
where t1.place_id=1
UNION ALL
select tag_id,0
from T1
where not exist (select 1 from T2 where user_id=100 and tag_id=4)
and tag_id=4;
编辑:我的问题不完整,还有一些案例遗漏了。这是一个例子(感谢@a_horse_with_no_name):http://sqlfiddle.com/#!12/67042/4
谢谢!
tag_id = 4
的行将被外连接返回。您只需要使用coalesce()
将null
值转换为0
即可。请参见此处的示例:http://sqlfiddle.com/#!12/ed7bf/1 - user330315