我有两张桌子:
学院(id)和users_colleges(user_id,college_id)
我想选择当前用户没有的所有大学(user_id!= @current_user)按user_colleges表中的匹配数排序,即使它是0。
我正在尝试但没有成功:
SELECT b.id, COUNT(b.id) AS count
FROM (`users_colleges` AS a)
RIGHT JOIN `colleges` AS b ON `b`.`id` = `a`.`college_id`
GROUP BY `b`.`id`
ORDER BY COUNT(b.id) DESC
这是回归所有大学订购的正确方法。问题是没有匹配计数的大学会返回1(应该是0),而且它也会返回用户已经拥有的大学。
答案 0 :(得分:1)
您应该计算表中外部连接的字段。这意味着当连接失败时它不会计算NULL值。
SELECT c.id, COUNT(uc.college_id) AS count
FROM colleges AS c
LEFT JOIN users_colleges AS uc
ON c.id = uc.college_id
GROUP BY c.id
ORDER BY COUNT(uc.college_id) DESC
要不返回用户已有的大学,您可以添加WHERE子句:
WHERE NOT EXISTS
(
SELECT *
FROM users_colleges AS uc2
WHERE uc2.college_id = c.id
AND uc2.user_id = '42'
)