选择不包含子项的文章的可用父项

时间:2017-11-06 10:38:13

标签: php mysql

我有一张文章(文章树)。让我们说它有id,parent_id和name。

enter image description here

对于文章的编辑形式,我想获得可用父文本的列表。我不能只列出所有文本,因为文章不能是它自己子项目的子项目。

有没有办法使用MySQL获取该列表?

1 个答案:

答案 0 :(得分:0)

SELECT * FROM articles WHERE id NOT IN (

SELECT DISTINCT articles.id FROM
(
    SELECT
        @row_num := @row_num + 1 AS row_num, 
        IF(@last_id <> my_list.id, @id := my_list.id, @id) AS path_id,
        @last_id := my_list.id AS id,
        @id := (SELECT DISTINCT parent_id FROM articles WHERE id = @id) AS parent_id
    FROM
        (SELECT @id := 0, @last_id := 0, @row_num := 0) AS vars,
        (SELECT id FROM articles) AS my_loop,
        (SELECT id FROM articles) AS my_list
) AS t

INNER JOIN articles 
ON t.id = articles.id 
WHERE path_id = :id
)