簡體   English   中英

在mysql或Mariadb中轉換查詢

[英]transform query in mysql or Mariadb

我需要將以下查詢從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中使用帶有x的include,option和

該查詢是可移植的,除了查詢提示option (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開始,支持通用表表達式。

暫無
暫無

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

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