mysql - 选择产品并加入类别分层
问题描述
我的数据库中有两个表:
create table category (id integer, name text, parent_id integer);
create table product (id integer, name text, category integer, description text);
insert into category
values
(1, 'Category A', null),
(2, 'Category B', null),
(3, 'Category C', null),
(4, 'Category D', null),
(5, 'Subcategory Of 1', 1),
(6, 'Subcategory Of 5', 5),
(7, 'Subcategory Of 5', 5),
(8, 'Subcategory of D', 4)
;
insert into product
values
(1, 'Product One', 5, 'Our first product'),
(2, 'Product Two', 6, 'Our second product'),
(3, 'Product Three', 8, 'The even better one');
我怎样才能这样返回:
product_id | product_name | root_category | category_path
-----------+--------------+---------------+-----------------------------
1 | Product One | 1 | /Category A/Subcategory Of 1
2 | Product Two | 1 | /Category A/Subcategory of 5/Subcategory of 6
我在类别表中使用“WITH RECURSIVE”,但找不到将产品表与 1 次查询相结合的方法。我从这里使用示例
最好的方法是什么?
解决方案
假设你有 MariaDB 10.2 或更高版本,你去吧:
with recursive pt (root_id, id, path) as (
select id, id, concat('/', name) from category where parent_id is null
union all
select pt.root_id, c.id, concat(pt.path, '/', c.name)
from pt join category c on c.parent_id = pt.id
)
select p.id, p.name, pt.root_id, pt.path
from pt
join product p on pt.id = p.category;
结果:
id name root_id path
-- -------------- ------- ---------------------------------------------
1 Product One 1 /Category A/Subcategory Of 1
2 Product Two 1 /Category A/Subcategory Of 1/Subcategory Of 5
3 Product Three 4 /Category D/Subcategory of D
推荐阅读
- javascript - 如何将 onclick 事件附加到从 vuejs "v-for=" 生成的每个项目以显示或隐藏其内部元素
- flutter - 如何修复颤动中的底部导航?
- python - 打印函数和调用涉及 Python 字典的函数的区别
- c++ - 什么 file.read(reinterpret_cast
(&variableName), sizeof(variablename)) 在 C++ 中用于读取图像吗? - python - 如何对 Python 输入字符串设置约束
- hadoop - 使用java代码调用pig store无法运行store命令(嵌入式模式)
- java - 如何在 Spring Data Cassandra 中对数据进行分页?
- python - 如果任何作业在 python 中失败,如何退出进程?
- java - 使用第三方 JAR 运行 Java
- python - python提取具有给定正则表达式格式的文件