将我的问题简化为一个小标题有点困难,因此,如果标题没有意义,我深表歉意。
无论如何,这是问题所在:
$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
的issues.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/