将我的问题简化为一个小标题有点困难,因此,如果标题没有意义,我深表歉意。

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

 $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.ticketidissues.id的行数。我对LEFT JOIN favorites的使用不是要获得我刚才提到的内容,而是要获取客户端是否喜欢此问题,因此是favorites.userid AS favorited部分。

我尝试执行以下操作:(为了便于阅读,我一次将其以项目符号形式显示)


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


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

最佳答案

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


那应该可行,我只是使用子查询来获取收藏夹数

关于mysql - 行计数一个JOINed列而不影响返回的行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3107993/

10-09 18:55