mysql - select语句中的CTE递归查询

标签 mysql

我有两台 MySQL 服务器版本 8.0,一台用于本地开发,另一台在 Heroku 实例上,更准确地说,在 Heroku 上我正在使用名为 JAWSDB 的服务。 .

对于我的项目,我必须使用以下 CTE 查询,因为表 tree_struct 的结构是分层的。

查询的目的是,对于tree_struction中的每一行,我必须获取其所有子级,然后计算user_roles表中存在多少用户该特定行及其子行。

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实例上它给了我以下错误:

where 子句中未知列 mtr.id

有人知道导致此错误的原因吗?

提前致谢,并对我的英语不好表示歉意。

最佳答案

您在 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用于子查询和最外层查询。好的做法是为您使用的每个表引用创建一个唯一的别名。

此外,您在应检查层次结构根节点的自引用的情况下也有拼写错误:

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

关于mysql - select语句中的CTE递归查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56184132/

相关文章:

mysql - Zend2 和 Doctrine2 的 MAMP PDO_MySql 错误

mysql - SQL - CONCAT 与 IF 语句返回 1583 错误

Mysql计算总分钟数

mysql - MySQL 查询中的日期/字符串差异

mysql - Docker 撰写 MySql 初始化脚本不执行

php - 如何解决ms-access到mysql数据传输中的阿拉伯编码问题?

php - 如何使用 backbone.js 和 php 将数据保存到 mysql 数据库中

php - 帮助理解 php 链接

php - 使用 ajax 进行多项选择

mysql - 在嵌套集模型中排序 sibling