1. 条件过滤 & Having

表结构

#tab_a

sql典例分析

#tab_b

sql典例分析

 

表关系

tab_a.id = tab_b.relation_id

表数据

sql典例分析

sql典例分析

需求

查新把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

结果

sql典例分析

问题

当tab_a的id与tab_b的member_id存在1对多的关系时就不行了,如tab_b

sql典例分析

再做上面的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

结果

sql典例分析

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 =b.order_id;

 

  

 

相关文章:

  • 2022-12-23
  • 2022-02-27
  • 2021-11-23
  • 2021-08-21
  • 2022-01-21
  • 2022-12-23
猜你喜欢
  • 2021-04-25
  • 2021-06-29
  • 2021-06-22
  • 2021-07-21
  • 2021-06-23
相关资源
相似解决方案