我有两张桌子
1)master\_category cat_id cat_name
------------------------------
1 Mobiles
2 Motorola
3 Microsoft
4 Mobile Accessories
5 Samsung
6 Sony
7 Samsung Accessories
8 Galaxy S6
9 Laptops
10 HP
11 Sony Vaio
12 Dell
13 Dell Accessories
--------------------------------------------2) master_category表中的category_group(在此表中分组类别主数据- main_group和Sub_group是cat_ids )。
id Main_group Sub_group
-----------------------------------------------------
1 1 2
2 1 3
3 1 4
4 1 5
5 1 6
6 4 7
7 5 8
8 9 10
9 9 11
10 9 12
11 12 13
---------------------------------------------在category_group类别中,移动有摩托、微软、三星等子类别,移动配件和移动设备有三星配件子类别,三星也有星系s6亚类。
笔记本电脑也是这样分组的。
当我搜索mobiles时,我需要编写一个查询来获得如下结果
cat_id cat_name
-------------------------------
2 Motorola
3 Microsoft
4 Mobile Accessories
5 Samsung
6 Sony
7 Samsung Accessories
8 galaxy s6
---------------------------------------------当我搜索笔记本电脑时,我需要得到如下结果
cat_id cat_name
----------------------------------
10 HP
11 Sony Vaio
12 Dell
13 Dell Accessories
---------------------------------------------发布于 2015-09-01 20:51:15
正如我已经标记的,我相信这是https://stackoverflow.com/a/192462/4421474的副本
但是,由于这个问题有特定的数据集,下面是我的方法(不是通用的,而是有用的)。
http://sqlfiddle.com/#!9/2787a/1
SELECT names.*
FROM master_category mc
LEFT JOIN category_group sc #level1
ON sc.main_group = mc.cat_id
LEFT JOIN category_group sc2 #level2
ON sc2.main_group = sc.sub_group
LEFT JOIN master_category names
ON sc.sub_group = names.cat_id
OR sc2.sub_group = names.cat_id
where mc.cat_name = 'Mobiles'
order by names.cat_id;发布于 2015-09-01 14:20:00
这并不复杂,您必须使用别名,否则您将得到类似于:“字段列表中的'id‘列是模棱两可的’‘(希望我没有错误):
select products.id,products.cat_name from category_group
join master_category as category on master_category.cat_id=category.Main_group
join master_category as products on master_category.cat_id=products.Sub_group
where category.cat_name='Mobiles'还请看以下内容:http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
https://stackoverflow.com/questions/32333940
复制相似问题