gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:00:55 26 4
gpt4 key购买 nike

我有一个选择查询,它应该返回连接到多个团队 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

最佳答案

使用具有适当连接条件的显式连接

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

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

关于MYSQL IN 语句在选择查询中返回重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29916571/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com