1

我有一个查询:

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;

它必须从列中选择与 sql 计算的列不同的所有user_id' 。usersfollowers_count

但问题是我收到错误消息

Error Code: 1054. Unknown column 'b.user_id' in 'on clause'

我做错了什么?非常感谢您的帮助。

4

1 回答 1

0

你的意思是uf.user_id = b.user_id代替uf.following_id = b.user_id吗?无论如何,user_follow桌子是干什么用的?

同意草莓,你最好使用显式连接。它们更容易阅读和理解。以下是您可能提到的内容(请注意,user_follow根本没有使用 table):

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

于 2013-05-10T09:57:18.560 回答