mysql - 在 mysql 或 Mariadb 中转换查询

标签 mysql sql-server

我需要将以下查询从 SQL Server 2012 转换为 MySQL,我没有 SQL Server 转录经验,所以我发现很难弄清楚。

表格详细信息,

create table T
(
 Id int primary key,
 ParentId int,
 Name varchar(10),
 ProductCount int
);

insert into T values
(1, -1, 'Cars',    0),
(2, -1, 'Bikes',   1),
(3,  1, 'Ford',    10),
(4,  3, 'Mustang', 7),
(5,  3, 'Focus',   4);

   create index IX_T_ParentID on T(ParentID) include(ProductCount, Id);

Sql Server 查询,

with C as
(
select T.Id,
     T.ProductCount,
     T.Id as RootID
 from T
 union all
 select T.Id,
     T.ProductCount,
     C.RootID
 from T
 inner join C 
  on T.ParentId = C.Id

 )
select T.Id,
   T.ParentId,
   T.Name,
   T.ProductCount,
   S.ProductCountIncludingChildren
from T
inner join (
         select RootID,
                sum(ProductCount) as ProductCountIncludingChildren
         from C
         group by RootID
         ) as S
 on T.Id = S.RootID
 order by T.Id
 option (maxrecursion 0);

我从未像 SQL 中那样使用过 include、option 和 x

最佳答案

此查询是可移植的,除了查询提示选项(maxrecursion 0);:

with C as
(
select T.Id,
     T.ProductCount,
     T.Id as RootID
 from T
 union all
 select T.Id,
     T.ProductCount,
     C.RootID
 from T
 inner join C 
  on T.ParentId = C.Id

 )
select T.Id,
   T.ParentId,
   T.Name,
   T.ProductCount,
   S.ProductCountIncludingChildren
from T
inner join (
         select RootID,
                sum(ProductCount) as ProductCountIncludingChildren
         from C
         group by RootID
         ) as S
 on T.Id = S.RootID
 order by T.Id

从MySQL 8.0开始支持公共(public)表表达式。

关于mysql - 在 mysql 或 Mariadb 中转换查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57467849/

相关文章:

c# - 有没有办法用 C# 以编程方式发布 rdl 报告?

mysql - 仅选取 WHERE 子句内 IF 语句中的第一个值

mysql - Tomcat 服务器与 Mysql 5.5 连接

MySQL 服务器最大化内存,Galera 集群

mysql - 如何使用 MYSQL 查询结果创建公式

php - Ios-App 从 Liferay DB 获取数据

sql-server - 数据类型 date 的日期函数 dateadd 不支持日期部分小时

sql-server - 最适合短命列的索引

c# - 如何在 Linq 或 Lambda 中创建 Stuff 和 XML PATH(SQL)

ios - 如何通过Objective C连接到SQL Server