Mysql Distinct连接记录不匹配或根本没有连接数据

时间:2014-11-14 22:03:26

标签: mysql join distinct

我有两个表:作者和帖子。作者可以有几个帖子(1:N)。

Authors:
- id
- name

Posts:
- id
- authors_id
- post_type

我需要检索他们的post_type不属于某种类型的所有作者,让我们说“Type1”,逻辑上需要包含没有帖子的作者。

我目前正在尝试这个:

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加上任何其他类型帖子的作者。

查询中是否可以这样做?

2 个答案:

答案 0 :(得分: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')

答案 1 :(得分: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