2014-11-14 26 views
0

加入数据我有两个表:作者和文章。作者可以有几个职位(1:N)。Mysql的鲜明加入的不匹配的记录,或者没有在所有

Authors: 
- id 
- name 

Posts: 
- id 
- authors_id 
- post_type 

我需要检索所有的作者,他们的post_type是某种类型的没有,可以说“类型1”,这将由逻辑需要包括作者没有职位的。

我现在试试这个:

Select DISTINCT a.* 
from authors a 
LEFT JOIN posts p ON p.authors_id = a.id 
WHERE 
p.post_type <> 'TYPE1' 
OR p.authors_id IS NULL 

这将返回正确里面有所有作者:

- no posts at all 
- or have only posts not of TYPE1 
- and will not show authors having only posts of TYPE1 

但是:它还将返回那些谁拥有TYPE1加任何其它类型的讯息的作者。

这是可能的查询?

回答

1

我认为这应该工作:

Select DISTINCT a.* 
from authors a 
LEFT JOIN posts p ON p.authors_id = a.id 
WHERE 
a.id NOT IN (SELECT p.authors_id from authors a INNER JOIN posts p ON p.authors_id = a.id WHERE p.post_type = 'TYPE1') 
+0

按预期工作,谢谢你乔改变你查询了一下! – gb5256 2014-11-15 10:30:38

0

您可以通过获取分组第一,然后加入到它

Select DISTINCT a.* 
from authors a 
LEFT JOIN 
(
select authors_id, group_concat(post_type order by post_type) as post_list 
from posts 
group by authors_id 
having post_list not like 'TYPE1%' 
) tab ON tab.authors_id = a.id 
WHERE tab.authors_id IS NULL 
相关问题