簡體   English   中英

select語句中的CTE遞歸查詢

[英]CTE recursive query in select statement

我有兩個MySQL服務器版本8.0,一個用於本地開發,另一個用於Heroku實例,更准確地說是Heroku我正在使用一個名為JAWSDB的服務。

對於我的項目,我必須使用以下CTE查詢,因為表tree_structure的結構是分層的。

查詢的目的是,對於tree_structure中的每一行,我必須得到它的所有子tree_structure ,然后計算user_roles表中有多少用戶存在於該特定行及其子tree_structure

SELECT mtr.id,
       mtr.parent_id,
       mtr.name,
       mtr.manager_id,
       CONCAT(users.nome, ' ', users.cognome) as resp_name,
       (
           with recursive cte (id, name, parent_id) as (
               select id,
                      name,
                      parent_id
               from tree_structure as tr_rec
               where tr_rec.parent_id = mtr.id
                 and tr_rec.session_id = '2018'
               union all
               select tr.id,
                      tr.name,
                      tr.parent_id
               from tree_structure as tr
                        inner join cte
                                   on tr.parent_id = cte.id
               WHERE tr.session_id = '2018'
           )
           select count(distinct (user_id))
           from user_roles as ur_count
           where ur_count.structure_id in (select distinct(id) from cte)
       )                                  as utenti
FROM tree_structure as mtr
         LEFT JOIN users ON mtr.manager_id = users.id
WHERE level = 0

問題是在我的本地服務器上它可以工作,而在heroku實例上,它給我帶來了以下錯誤:

unknow columns mtr.id in where clause

有人對導致此錯誤的原因有任何想法嗎?

提前謝謝,抱歉我的英語不好。

您在CTE中有一個不明確的表格引用:

SELECT 
  ....   
    (with recursive cte (id, name, parent_id) as (
     ....
       from tree_structure as tr_rec        -- here you have aliased the table
      where tr_rec.id = tree_structure.id  -- here you refer to the table and its alias
        and tr_rec.session_id = '2018'
      union all
      ....
    )
    ....
 ) as utenti
....

表tree_structure用於subselect和最外面的select。 好的做法是為您使用的每個表引用創建一個唯一的別名。

此外,您還應該檢查錯誤根源節點的自引用條件:

where tr_rec.id = tr_rec.parent_id
  and tr_rec.session_id = '2018'

好的,我發現了查詢錯誤的原因。 顯然,自MySQL版本8.0.14以來,他們引入了在子查詢中使用外部參數的支持。

我的本地版本是8.0.16,但在線版本是8.0.11所以因為這個我的查詢不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM