MYSQL IN语句在select查询中返回重复项
我有一个select查询,它应该返回连接到多个团队ID的新闻。为此,我使用IN语句和所选的团队ID。例如,在本例中,我选择了id为1和2的团队,如您所见 问题是,两个团队可能会联系到同一条新闻,因此我不想重复同一条新闻?我如何确保即使团队可能连接到同一条新闻,也没有重复的新闻MYSQL IN语句在select查询中返回重复项,mysql,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
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
使用带有适当连接条件的显式连接
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
请注意,在执行join时,如果在其他表中多次预设了项目,即1,2
,则它将出现多次。如果您想摆脱这种情况,请使用groupby
where t.id in (1,2)
group by t.id
但是这将从关联ID的联接表中选择随机数据
1,2
那么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
这是因为它是笛卡尔积