如何进行嵌套查询?
有一个表 users,并且有一个字段 informed_by_id 显示邀请该用户的人的用户 ID。需要创建一个 MySQL 查询,返回包含用户所有字段的行以及显示每个用户邀请了多少人的 informs_count 字段。 像这样的事情:
SELECT
User.*, Count.count
FROM
users AS User,
(
SELECT COUNT(*) AS count FROM users WHERE users.invited_by_id=User.id
) AS Count;
这个不能用,所以我需要一个能用的。
Have a table users and there is a field invited_by_id showing user id of the person who invited this user. Need to make a MySQL query returning rows with all the fields from users plus a invites_count field showing how many people were invited by each user.
Something like this:
SELECT
User.*, Count.count
FROM
users AS User,
(
SELECT COUNT(*) AS count FROM users WHERE users.invited_by_id=User.id
) AS Count;
This one is not working so I need a working one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,首先,
count
是 sql 中的保留字,因此您不能将其用作表别名(除非您以某种方式引用它但不这样做)。其次,解决此问题的真正方法是在子查询中引入 GROUP BY 子句。试试这个:
这里有一个关于 MySQL 的肮脏小秘密:它允许您使用 GROUP BY 语句作弊,并选择不在 GROUP BY 列表中且不在聚合函数。其他 RMDMS 不允许您这样做。
Ok, first of all,
count
is a reserved word in sql so you can't use it as a table alias (unless you quote it in some way but don't do that). Secondly, the real way to solve this problem is to introduce aGROUP BY
clause in your subquery.Try this:
Here is a dirty little secret about MySQL: It lets you cheat with the
GROUP BY
statement and select columns that are not in theGROUP BY
list and also not in aggregate functions. Other RMDMSes don't let you do this.