【发布时间】:2014-10-01 14:49:04
【问题描述】:
我找到了这个帖子:Finding all parents in mysql table with single query (Recursive Query)。 它描述了如何轻松找到所有独生子女的父母。
我想知道是否可以获取通过查询找到的多个孩子的所有父母。
例如。我们有一个如下表:
table1
--------------------
id | name | parent_id
1 | aaa | null
2 | bbb | 1
3 | bbb | 1
4 | ccc | 3
5 | ccd | 1
我们希望找到名称包含“cc”的项目的所有父项
select id from table1 where name like '%cc%';
# ids fetched
# => 4, 5
# parents what we're looking for
# for id = 4 -> 4,3,1 | for 5 -> 5,1
我尝试了类似的方法,但没有成功:
SELECT T2.id, T2.name, T2.parent_id, T1._id, T1.lvl
FROM (
SELECT
@r AS _id,
(SELECT @r := parent_id FROM table1 WHERE id = _id) AS parent_id,
@l := @l + 1 AS lvl
FROM
(SELECT @r := l.id from table1 l where name like '%cc%') tmp,
table1 t
WHERE @r <> 0) T1
JOIN categories T2
ON T1._id = T2.id;
提前致谢。
编辑,因为我不够清楚,我尽可能简化了示例,所以我错过了我真正需要的关键部分:
我需要找到的是相关表的任何父级都将标志设置为 true。 我有 3 张桌子:
categories
---------------------
id | name | parent_id | flag
articles
---------------------
id | name
# intersection between categories and related articles
category_articles
---------------------
category_id | article_id
如您所见,文章可以有多个类别。 我想列出按任何父标志 asc 排序的文章(首先为真,在它们之后为假),然后按名称。当与文章相关的类别之一或与类别相关的任何父级将标志设置为真时,“标志”列应等于真。 示例结果:
articles
id | name | flag
1 | aaa | true
5 | ccc | true
2 | hhh | true
3 | bbb | false
4 | zzz | false
我需要在一个查询中执行此操作以在不中断排序的情况下应用限制和偏移量。
【问题讨论】: