1

I have a select query which is suppose to return news which is connected to several team ids. For this i'm using the IN statement with the selected team ids. For instance in this case i've chosen the teams with the id's 1 and 2 as you can see

The issue is that the teams might be connected to the same news and therefor i dont want duplicates of the same news? How can i make sure that there are not duplicate news even though the teams might be connected to the same news?

 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  
1
  • 1
    Thats because its doing Cartesian product Commented Apr 28, 2015 at 10:19

2 Answers 2

1

Use explicit join with proper joining conditions

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

Note that while doing join if the items i.e. 1,2 are preset multiple times on other tables then it will appear multiple times. If you want to get rid of this use group by

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

But this will choose random data from the joined tables for the associated ids 1,2.

Sign up to request clarification or add additional context in comments.

Comments

0

What about DISTINCT? In order to avoid duplicate results:

    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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.