关于sqlserver数据库中的with as 语句使用union all提问

关于sqlserver数据库中的with as 语句使用union all提问

目前工作中需要把一些存储过程从sqlserver迁到mysql,不熟悉sqlserver,遇到这样的一条语句
我不知道这条语句是怎么执行的

WITH DEPT AS
        (select cost_name,department_id,cost_code,parent_cost_code
            from2
            where cost_code  in ('t')
            UNION ALL
            SELECT c.cost_name,c.department_id,c.cost_code,c.parent_cost_code
            FROM DEPT d,表2 C 
            WHERE d.cost_code = c.parent_cost_code)
            select count(*) from DEPT;

运行结果条数是1100

img

我的解答思路和尝试过的方法

我自己研究一天也百度过,硬是找不到方法
写了一条mysql的

SELECT COUNT(*) FROM (
                SELECT cost_name,department_id,cost_code
                FROM2
                WHERE cost_code  IN ('t')
                UNION ALL            
                SELECT c.cost_name,c.department_id,c.cost_code
                FROM
               (SELECT cost_code FROM2 WHERE cost_code  IN ('t')) d,bm_report_cost2 C 
                WHERE d.cost_code = c.parent_cost_code) AS s;

结果只有102条数据

img

他们的表数据是一致的,结果中sqlserver的cost_code字段有‘t’还有其他。mysql中的cost_code字段只有‘t’。
我把mysql的第二条WHERE cost_code IN ('t') 去掉后又比sqlserver的多了500条数据

现在我想他们出来的结果一致,mysql这边应该怎么写

这种是CTE递归实现,mysql需要8.x才支持这种写法,而且mysql的CTE递归需要加RECURSIVE

WITH RECURSIVE DEPT AS
        (select cost_name,department_id,cost_code,parent_cost_code
            from2
            where cost_code  in ('t')
            UNION ALL
            SELECT c.cost_name,c.department_id,c.cost_code,c.parent_cost_code
            FROM DEPT d,表2 C 
            WHERE d.cost_code = c.parent_cost_code)
            select count(*) from DEPT;

  1. select cost_name,department_id,cost_code,parent_cost_code from 表2 where cost_code in ('t') 执行有一个结果;
  2. SELECT c.cost_name,c.department_id,c.cost_code,c.parent_cost_code FROM DEPT d,表2 C WHERE d.cost_code = c.parent_cost_code;有一个执行结果;
  3. 两个进行联查union all;
  4. 第三步的结果作为DEPT, 然后去查询总共的条数。

看不到数据只能说想法:
1.按照sqlserver、mysql两个数据库的cost_code分组,看看条件为'T'的数据条数是否一致。
2.把sqlserver、mysql两个数据库的sql拆分开去执行,分析每一条sql是那一步出现数据缺失的原因。
3.个人觉得应该是两边数据不一致导致的,看你sql很简单且数据库也都支持这样写应该跟版本什么的没影响。

1.先查dept表中两个结果集 每个结果集和mysql这边查询的结果集数量是否有差异
2.1没问题后再查询两个结果集union all后的结果集数量是否相同