MySQL复杂的连接查询

时间:2015-09-01 14:14:41

标签: mysql

我有2张桌子    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)category_group(在此表中,分组类别主数据 - main_group Sub_group cat_ids 来自 master_category

   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 类别移动有子类别如motoroal,microsoft,samsung,移动配件和移动配件有子类三星配件,还有三星有子组galaxy s6

笔记本电脑也是这样分组的

当我搜索手机时,我需要编写查询以获得如下结果

 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
---------------------------------------------

2 个答案:

答案 0 :(得分:1)

它并不复杂,你必须加入别名,否则你会得到类似的东西:' Column' 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/

答案 1 :(得分:1)

正如我已经标记的那样,我认为这与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;