反正有没有在sql中获取自己的父表?

时间:2017-04-07 12:05:44

标签: mysql sql

我在mysql数据库中需要一些like this

就我而言,我需要来自:

ID | FIRST_REFERENCE  | description
1  | -1               | root
2  | 1                | other_child
3  | -1               | root
4  | 2                | child
5  | 1                | other_child
6  | 3                | child

我需要使用childID返回root,如果childID指向root,则返回child:

我试过了:

SELECT parent.ID 
FROM mytable as child
JOIN mytable as parent
ON child.FIRST_REFERENCE = parent.ID 
WHERE parent.FIRST_REFERENCE = '-1' AND child.ID = '6'

但它不起作用

然后我尝试了一个选择案例的解决方案:

  SELECT
   CASE FIRST_REFERENCE
   WHEN '-1' THEN ID
   ELSE SELECT rec.ID 
       FROM mytable as rec 
       WHERE rec.ID = main.FIRST_REFERENCE
   END as 'root'
  FROM mytable as main
  WHERE childID = '6'

但是我收到语法错误。

我哪里错了?

1 个答案:

答案 0 :(得分:2)

如果其他人遇到我的问题我用simle LEFT JOIN解决了:

SELECT CASE WHEN parent.ID is NULL THEN child.ID
        ELSE parent.ID
        END AS ID
FROM my table AS child 
LEFT JOIN my table AS parent ON 
  ((parent.ID = child.FIRST_REFERENCE AND parent.FIRST_REFERENCE =  '-1') OR 
  (child.FIRST_REFERENCE = '-1' AND parent.ID = NULL)) 
WHERE child.ID =  '6'