行计算JOINed列而不影响返回的行?

时间:2010-06-24 07:38:22

标签: mysql join count

将问题变成简短形式有点困难,所以如果标题没有意义,我会道歉。

无论如何,这是问题所在:

 $query = '
  SELECT issues.*, comments.author AS commentauthor, favorites.userid AS favorited FROM issues
  LEFT JOIN comments ON comments.issue = issues.id AND comments.when_posted = issues.when_updated
  LEFT JOIN favorites ON favorites.ticketid = issues.id AND favorites.userid = \'' . $_SESSION['uid'] . '\'
  ' . $whereclause . '
  ORDER BY issues.when_updated ' . $order;

不要介意它是PHP,因为我要求PHP帮助。

查询检索了一堆issues,我希望做的是获得favorites匹配favorites.ticketid的{​​{1}}行数。我对issues.id的使用不是为了得到我刚刚提到的内容,而是为了获得客户是否支持该问题,而不是LEFT JOIN favorites部分。

我尝试过以下操作:(一下子,我把它用于项目符号形式以便于阅读)

  • 复制现有的favorites.userid AS favorited并从重复的
  • 中删除用户ID检查
  • LEFT JOIN favorites添加到, COUNT(favorites.ticketid) AS favoritescount部分
  • SELECT添加到原始AS favorited以及将LEFT JOIN更改为favorites.userid

通过该尝试,我的查询最终只返回一行。

1 个答案:

答案 0 :(得分:0)

SELECT issues.*,
       comments.author AS commentauthor,
       favorites.userid AS favorited,
       (
           SELECT COUNT(favorites.id)
           FROM favorites
           WHERE ticketid = issues.id
       ) AS numfavorites
FROM issues
LEFT JOIN comments
    ON comments.issue = issues.id
    AND comments.when_posted = issues.when_updated
LEFT JOIN favorites
    ON favorites.ticketid = issues.id
    AND favorites.userid = ?uid

这应该有用,我只是使用子查询来获取收藏数