如何在单个表中获取某些特定行的所有父行

时间:2016-06-26 08:43:16

标签: php mysql mysql-workbench

http://prntscr.com/bl6oeo Structure of table

我可以通过以下查询获得id为1的所有类别的孩子。

SELECT
  GROUP_CONCAT(lv SEPARATOR ',')
FROM (
  SELECT @pv:=(
    SELECT GROUP_CONCAT(id SEPARATOR ',')
    FROM files WHERE parent_id IN (@pv)
  ) AS lv
  FROM files
  JOIN (
    SELECT @pv:=1)tmp WHERE parent_id IN (@pv)
  ) a

任何人都可以告诉我,我们怎样才能得到某些行的所有父母,例如第4行

1 个答案:

答案 0 :(得分:0)

我得到了答案...... :)

SELECT T2.id, T2.title
FROM (
    SELECT
        @r AS _id,
        (SELECT @r := parent_id FROM files WHERE id = _id) AS parent_id,
        @l := @l + 1 AS lvl
    FROM
        (SELECT @r := 4, @l := 0) vars,
        files h
    WHERE @r <> 0) T1
JOIN files T2
ON T1._id = T2.id
ORDER BY T1.lvl DESC