简体   繁体   中英

If statement in select using with join in MySQL

I have 3 tables which are news (id, title, descrption) , cat (id, title) , newscat (id, newsID, catID) . As you see each news can relate to any or some cats . I want one query to fetch all cat s and if cat is related to news 'checked'. I wrote this query:

SELECT
  c.id, c.title, IF (nc.newsID = $newsID, 'checked', null) as checked
FROM
  cat c
  LEFT JOIN newscat nc ON c.id = nc.catID

but this doesn't work. Some cat s come duplicate. What is the problem?

Using suggestion from Wr1t3r:

SELECT
  c.id, c.title, IF (COUNT(IF(nc.newsID=$NewsID,1,NULL)) > 0, 'checked', null) as checked
FROM
  cat c
  LEFT JOIN newscat nc ON c.id = nc.catID
  GROUP BY  c.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM