我找到了这个帖子:Finding all parents in mysql table with single query (Recursive Query) . 它描述了如何轻松找到所有单亲的父母 .
我想知道我是否可以为查询找到的多个孩子取得所有父母 .
例如 . 我们有一个像波纹管一样的 table :
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张 table :
categories
---------------------
id | name | parent_id | flag
articles
---------------------
id | name
# intersection between categories and related articles
category_articles
---------------------
category_id | article_id
如您所见,文章可以有多个类别 . 我想列出任何父标志asc首先排序的文章(先是true,后面是false),然后是名字 . 当与文章相关的类别或与类别相关的任何父类别之一将标志设置为true时,'flag'列应该等于true . 示例结果:
articles
id | name | flag
1 | aaa | true
5 | ccc | true
2 | hhh | true
3 | bbb | false
4 | zzz | false
我需要在一个查询中执行此操作以应用限制和偏移而不会破坏排序 .
1 回答
您可以在MySQL中使用
UNION
将多个select语句的结果合并到一个结果集中 .在这种情况下,您可以这样做: