拥有一个表用户,并且有一个字段invite_by_id显示邀请此用户的用户ID。需要使MySQL查询返回包含用户所有字段的行以及invites_count字段,以显示每个用户邀请的人数。 像这样:
SELECT
User.*, Count.count
FROM
users AS User,
(
SELECT COUNT(*) AS count FROM users WHERE users.invited_by_id=User.id
) AS Count;
这个没有用,所以我需要一个工作。
答案 0 :(得分:6)
SELECT u.*,
(
SELECT COUNT(*)
FROM users ui
WHERE ui.invited_by_id = u.id
) AS cnt
FROM users u
答案 1 :(得分:4)
好的,首先,count
是sql中的保留字,因此您不能将其用作表别名(除非您以某种方式引用但不要这样做)。其次,解决此问题的真正方法是在子查询中引入GROUP BY
子句。
试试这个:
SELECT user3.*, subquery.theCount FROM
users AS user3
INNER JOIN (
SELECT
user1.id, count(user2.id) AS theCount
FROM
users AS user1
LEFT OUTER JOIN
users AS user2 ON user2.invited_by_id=user1.id
GROUP BY user1.id
) AS subquery ON subquery.id=user3.id;
这是关于MySQL的一个肮脏的小秘密:它允许你使用GROUP BY
语句作弊,并选择不在GROUP BY
列表中的列,也不在聚合函数中。其他RMDMS不允许你这样做。
SELECT
user1.*, count(user2.id) AS theCount
FROM
users AS user1
LEFT OUTER JOIN
users AS user2 ON user2.invited_by_id=user1.id
GROUP BY user1.id;