需要帮助将以下SQL查询转换为MySQL而无需交叉应用方法

时间:2019-07-27 11:56:38

标签: mysql sql cross-apply

需要在MySQL上提取以下查询-

select ut.ID, aa.Name, ut.Parent, aa.Geneology,
convert(int,(len(aa.Geneology)-len(Replace(aa.Geneology,',','')))-1) 'Level'
from (select u.id, x.Name, x.Geneology
      from userDT u cross apply
           (select n.Geneology,n.Name
            from userDT n
            Where n.Geneology like '%' + u.Geneology + '%'
           ) x
      where u.id=3
     ) aa left join
     userDT ut
     on ut.Geneology = aa.Geneology";

UserDT表-

id  Name    Parent  Geneology
1   abc -   1,
2   def abc 1,2
3   ghi abc 1,3
4   jkl def 1,2,4
5   mno ghi 1,3,5
6   pqr def 1,2,6
7   stu ghi 1,3,7
8   vwx mno 1,3,5,8
9   xyz vwx 1,3,5,8,9

结果应该是这样-

ID  Name    Parent  Geneology   Level
3   ghi abc 1,3         0
5   mno ghi 1,3,5           1
7   stu ghi 1,3,7           1
8   vwx mno 1,3,5,8         2
9   xyz vwx 1,3,5,8,9   3

1 个答案:

答案 0 :(得分:0)

您可以将其转换为join。在MySQL语法中,我认为查询如下:

select ut.ID, aa.Name, ut.Parent, aa.Geneology,
       (len(aa.Geneology)-len(Replace(aa.Geneology, ',', '')))-1 as Level
from (select u.id, x.Name, x.Geneology
      from userDT u join
           userDT x
           on x.Geneology like concat('%', u.Geneology, '%')       ) x
      where u.id = 3
     ) aa left join
     userDT ut
     on ut.Geneology = aa.Geneology;

坦白说,我认为它在MySQL或SQL Server中都没有太大用处。您可能要问另一个问题,包括样本数据,所需结果以及要实现的逻辑的解释。