MYSQL IN语句在select查询中返回重复项

时间:2015-04-28 10:15:24

标签: mysql

我有一个select查询,它假设返回连接到多个团队ID的新闻。为此,我使用IN语句和选定的团队ID。例如,在这种情况下,我已经选择了id为1和2的团队,你可以看到

问题是团队可能连接到相同的新闻,因此我不想要相同新闻的重复?即使团队可能连接到相同的新闻,我怎样才能确保没有重复的新闻?

 SELECT news.id,
   news.title,
   news.url,
   news.image_url,
   news.date,
   news.news_text,
   website.url   AS website_url,
   website.image AS website_image
FROM   news,
       team,
       contain,
       website
WHERE  team.id IN ( 1, 2 )
       AND news.website_id = website.id
       AND team.id = contain.team_id
       AND contain.news_id = news.id
ORDER  BY news.date DESC
LIMIT  0, 30  

2 个答案:

答案 0 :(得分:1)

使用具有正确连接条件的显式连接

SELECT 
n.id, 
n.title, 
n.url, 
n.image_url, 
n.date, 
n.news_text, 
w.url as website_url, 
w.image as website_image 
from news n
join contain c on c.news_id = n.id
join team t on t.id = c.team_id
join website w on w.id = n.website_id
where  t.id in (1,2)
ORDER BY n.date DESC LIMIT 0, 30

请注意,在进行加入时,如果在其他表格上多次预设了项目1,2,那么它会多次出现。如果你想摆脱这种使用group by

where  t.id in (1,2)
group by t.id

但是,这将从联接表中为关联的ID 1,2选择随机数据。

答案 1 :(得分:0)

DISTINCT怎么样? 为了避免重复结果:

    SELECT DISTINCT news.id, news.title, news.url, news.image_url, 
news.date, news.news_text, website.url as website_url, 
website.image as website_image from news, team, contain, website 
WHERE team.id in (1,2)
 AND news.website_id = website.id
 AND team.id = contain.team_id
 AND contain.news_id = news.id 
 ORDER BY news.date DESC LIMIT 0, 30