mysql - 在子查询中使用查询中的列

标签 mysql sql

我有一个包含用户数据的表,每个用户都有其父用户。在我的上一个问题中,我想显示当前用户的两个级别的子用户,现在我需要显示每个用户的每个级别中的用户数量的表。我以为我可以编辑上一个问题的查询,但我无法让它工作。如何在子查询中使用 select 语句中的列?

我的查询:

SELECT c.id, c.nickname, c2.u1, c2.u2 
FROM favor_customer c, (
SELECT count(*) as u1 
FROM favor_customer u 
WHERE u.parent_id = c.id 
UNION ALL 
SELECT count(*) as u2 
FROM favor_customer u JOIN favor_customer uc ON uc.parent_id = u.id 
WHERE u.parent_id = c.id) c2

我在“where 子句”中收到未知列“c.id”

示例数据:

id  | nickname | parent_id
1   |   AAA    |   null
2   |   BBB    |    1
3   |   CCC    |    2
4   |   DDD    |    2

期望的输出:

id  | nickname | level_1 | level_2
1   |   AAA    |    1    |   2 
2   |   BBB    |    2    |   0
3   |   CCC    |    0    |   0
4   |   DDD    |    0    |   0

level_1 和 level_2 列是每个级别中的用户计数。 我做错了什么?

最佳答案

我正在考虑外连接和聚合:

select fc.id, fc.nickname,
       count(distinct fc1.id) as level1,
       count(distinct fc2.id) as level2
from favor_customer fc left join
     favor_customer fc1
     on fc1.parent_id = fc.id left join
     favor_customer fc2
     on fc2.parent_id = fc1.id
group by fc.id, fc.nickname;

关于mysql - 在子查询中使用查询中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59530918/

相关文章:

php - 将变量发送到表 PHP SQL

mysql - 如何将sql结果中的数据向下推送

sql - Golang 服务器 : send JSON with SQL query result that has variable number of columns

mysql - 将 2 个要求合并到 1 个查询中

php - mysql 不更新 html/php 中的信息

c# - 如何从Windows窗体应用程序C#将数据保存到xampp phpmyadmin mysql数据库

php - 用户注册失败后保留表单值

sql - 如何指定要在 SQLite 输出中使用的记录分隔符?

SQL - PHPmyadmin - 按 'id ascending' 更改表顺序 - 永久化

sql - 检查数据是否具有默认长度并且它在sql中是数字