sql典例分析
原创
©著作权归作者所有:来自51CTO博客作者mb6300b232419d1的原创作品,请联系作者获取转载授权,否则将追究法律责任
1. 条件过滤 & Having
表结构
#tab_a
#tab_b
表关系
tab_a.id = tab_b.relation_id
表数据
需求
查新把tab_a的ID对应的表tab_b的member_id找出来,当在表tab_b中找不到时,赋值为null
select tab_a.id,
case
when (SELECT count(member_id) from tab_b WHERE relation_id = tab_a.id ) = 0 then null
ELSE (SELECT member_id from tab_b WHERE relation_id = tab_a.id )
end as result
from
结果
问题
当tab_a的id与tab_b的member_id存在1对多的关系时就不行了,如tab_b
再做上面的sql查询是出现错误:
[Err] ERROR: more than one row returned by a subquery used as an expression
问题
如何找到tab_a中的id 对应的tab_b中的member_id有多个?
select tab_a.id, count(*) from tab_a, tab_b where tab_a.id=tab_b.relation_id group by tab_a.id having count(*)>1
结果
2. 一个表的结构作为另一个表的条件
update orders p, (select order_id, sum(count) as cnt from job_info group by order_id) b set p.count_raw = b.cnt where p.id