选择子查询以检查子行是否存在

时间:2016-03-25 23:11:28

标签: mysql

我想检查子行是否存在3级,2级是1级还是1级。

select max(
 case 
  (select row from category where relatedRow in (select row from category where relatedRow=?)) is not null then 3
  (select row from category where relatedRow=?) is not null then 2
  (select row from category where row=?) is not null then 1
  else 0 end
) as level from category

我该如何做到这一点?

此查询如下。如果有行具有相关行(孙子)的相关行,则level = 3。如果有相关的行(子),级别2.如果有一行=? (父级),级别1.如果没有父级(重影),级别为0。

1 个答案:

答案 0 :(得分:0)

您可以使用自联接来获取预期值,例如:

String.valueOf(input.charAt(i))

简而言之,要转到select c1.row, c2.row, c3.row from category c1 left join category c2 on c1.row = c2.related_row left join category c3 on c2.row = c3.related_row where c1.row = 1; 级别,您需要自行加入表格nth次。

以下是 SQL Fiddle