根据列过滤其他表中的数据,以及同一表中的空值?

mnowg1ta  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(224)

我有两张tabledocs和geo
文档表:

id  category company headorg type
1   1        20      4       aaa
2   1        null    4       bbb
3   null     20      4       ccc
4   null     20      4       ddd
5   2        null    4       bbb
6   null     20      4       ccc

地理表:

id  category investor headorg 
1   1        20       4       
2   1        21       4      
3   1        22       4      
4   2        21       4      
5   2        22       4

现在我要根据传递的company=20查询docs表,还要根据category检查geo表。
在这里,docs.company只不过是geo.investor
例如,以类别1为例,在类别1的筛选表geo中,我们有20个投资者,因此我们应该获得文档记录1,2,即使公司在docs表中为空。如果公司20的类别为空,即文档记录3、4、6
所以我的查询应该返回1,2,3,4,6
我写了这个,但是我得到了所有的记录1,2,3,4,5,6

SELECT  * FROM doc d where (company is null  or company = 20) 
and 20 in ( select geo.investor from geo join doc d on d.category = geo.category)
bejyjqdl

bejyjqdl1#

我想你想要:

SELECT d.*
FROM doc d 
WHERE d.company = 20 OR 
      d.category = (SELECT g.category FROM geo g WHERE g.investor = 20);

或者,用一个 JOIN :

select d.*
from doc d left join
     geo g
     on d.category = g.category and g.investor = 20
where d.company = 20 or g.category is not null;

相关问题