[英]Use column from query in subquery
我有一個包含用戶數據的表,每個用戶都有它的父用戶。 在我的最后一個問題中,我想為當前用戶顯示兩個級別的子用戶,現在我需要顯示每個用戶每個級別的用戶數表。 我以為我可以編輯上一個問題中的查詢,但我無法讓它工作。 如何在子查詢中使用 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
我Unknown column 'c.id' in 'where clause'
收到Unknown column 'c.id' in 'where clause'
樣本數據:
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;
當然這可以通過重復連接來完成,但是當涉及到分層數據時,遞歸查詢是一種更適合這項工作的工具
with recursive customer_relation AS
(
select id,
parent_id ancestor_id,
1 distance
from favor_customer
where parent_id is not null
union all
select c.id, r.ancestor_id, distance+1
from favor_customer c inner join customer_relation r on r.id = c.parent_id
)
select c.id,
c.nickname,
(select count(*) from customer_relation where ancestor_id = c.id and distance = 1) level_1,
(select count(*) from customer_relation where ancestor_id = c.id and distance = 2) level_2
from favor_customer c
注意:您需要子選擇(可以用連接和分組替換),因為您需要在它們自己的列中包含 level_1、level_2。 如果您需要的是組合 id-level-count,這將變得更加優雅。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.