我有一个问题:
SELECT b.user_id, b.active FROM users b
WHERE b.followers_count != (SELECT COUNT(*)
FROM (SELECT u.user_id
FROM user_follow uf,users u,user_follow_request ufr
WHERE
uf.following_id = b.user_id AND
uf.following_id = ufr.friend_id AND
ufr.status = 'approved' AND
ufr.user_id = u.user_id AND u.user_id != b.user_id AND u.active != 0
GROUP BY u.user_id) a)
AND b.active = -1 limit 5;
必须从user_id
中选择与sql计算的列中users
不同的所有followers_count
。
但问题是我收到错误消息
Error Code: 1054. Unknown column 'b.user_id' in 'on clause'
我做错了什么?非常感谢您的帮助。
答案 0 :(得分:0)
您的意思是uf.user_id = b.user_id
而不是uf.following_id = b.user_id
吗?无论如何,user_follow
表用于什么?
同意草莓,你最好使用显式连接。它们更容易阅读和理解。以下是您可能提到的内容(请注意,user_follow
表根本没有使用过):
SELECT u.user_id, u.followers_count, IF(ISNULL(uafc.actual_fc),0,uafc.actual_fc) AS afc
FROM users AS u
LEFT JOIN (
SELECT u.user_id AS user_id, COUNT(*) AS actual_fc
FROM users AS u
JOIN user_follow_request AS ufr
ON ufr.friend_id = u.user_id
JOIN users AS fu
ON fu.user_id = ufr.user_id
WHERE ufr.user_id != u.user_id
AND ufr.status = 'approved'
AND fu.active != 0
GROUP BY u.user_id, u.followers_count
) AS uafc
ON uafc.user_id = u.user_id
WHERE u.followers_count != IF(ISNULL(uafc.actual_fc),0,uafc.actual_fc)
;
对于NULL解决方法可能有一些更好的解决方案。
在SQLFiddle上查看:http://sqlfiddle.com/#!2/71f6c/3