简体   繁体   English

选择语句中的if语句与MySQL中的join一起使用

[英]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) . 我有3个表,分别是news (id, title, descrption)cat (id, title)newscat (id, newsID, catID) As you see each news can relate to any or some cats . 如您所见,每个news都可能与任何或某些cats I want one query to fetch all cat s and if cat is related to news 'checked'. 我想要一个查询来提取所有cat ,如果catnews “ 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. 有些cat会复制。 What is the problem? 问题是什么?

Using suggestion from Wr1t3r: 使用来自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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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