gpt4 book ai didi

MySQL复杂连接查询

转载 作者:行者123 更新时间:2023-11-29 06:23:23 25 4
gpt4 key购买 nike

我有2张 table
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(在此表中分组类别主数据 - ma​​in_groupSub_group 是来自 ma​​ster_categorycat_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 类别中,Mobile 有子类别,例如 motoroal、microsoft、samsung、mobile accessories 和 mobile accessories 有子类别 samsung accessories,三星也有子类别 galaxy 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
---------------------------------------------

最佳答案

正如我已经标记的那样,我相信这是 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;

关于MySQL复杂连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32333940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com