如果语句在select中使用带有MySQL的连接

时间:2015-03-10 16:58:26

标签: mysql

我有3个表news (id, title, descrption)cat (id, title)newscat (id, newsID, catID)。如您所见,每个news都可以与任何或cats相关联。我想要一个查询来获取所有cat,如果catnews'已检查'相关联。我写了这个问题:

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

但这不起作用。有些cat是重复的。有什么问题?

1 个答案:

答案 0 :(得分:1)

使用来自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