There are news and categories. A news can belong to many categories, or have no category at all. I need to query for all news that don't belong to specific category (ie 2) (If news belongs to categories 2 and 3 we still don't want it).
It seems that I solved it this way, but I'm not very experienced with SQL, so will be very grateful for any ideas and critique. Sorry for maybe trivial and uninteresting question.
SELECT * FROM news n
LEFT JOIN news_cats nc ON n.id = nc.cat_id
WHERE n.id NOT IN (SELECT news_id FROM news_cats WHERE news_cats.cat_id = 2)
GROUP BY n.id;
SELECT * FROM news n
LEFT JOIN news_cats nc ON n.id = nc.cat_id
WHERE news_cats.cat_id <> 2
GROUP BY n.id;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.