gpt4 book ai didi

mysql - 基于外键的SELECT,更改引用

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

我有 2 个表:EquipmentEquipment_Type:

+-------------------------------+
| EqId [PK] | ETId [FK] | EqNum |
+-------------------------------+
| 1 | 1 | ABC |
| 2 | 1 | DEF |
| 3 | 3 | GHI |

+-------------------------------+
| ETId [PK] | Code | Discipline |
+-------------------------------+
| 1 | MOT | ELEC |
| 2 | MOT | MECH |
| 3 | SW | ELEC |

所以从这个例子中,我们可以看到我们的两个设备都是电动机。

但是,由于最初人群的误解,所有设备类型都被确定为 ELEC 学科。从那时起,MECH设备已被识别,我必须找到Equipment_Type表中所有重复的设备,并将它们更改为引用 >MECH 设备类型改为。

我尝试过这个:

SELECT * FROM Equipment EQ 
INNER JOIN Equipment_Type ET on ET.ETId = EQ.ETId
WHERE ET.Discipline = 'MECH';

这(显然)不返回任何结果 - 与所有其他 JOIN 查询一样。

我想要实现的搜索将选择具有ELEC设备类型且的设备>MECH 设备类型。我意识到这需要嵌套查询,但我不确定将其放置在哪里。

所以搜索应该返回:

+---------------------------+
| EqNum | ETId | Discipline |
+---------------------------+
| DEF | 1 | ELEC |

因为该条目需要更改为 MECH 规则(即 ETId = 2 而不是 1)

最佳答案

这是一种聚合类型以获得具有两个学科的代码的方法:

select e.*
from equipment e join
equipment_type et
on e.etid = et.etid join
(select et.code
from equipment_type et
group by et.code
having sum(discipline = 'MECH') > 0 and sum(discipline = 'ELEC') > 0
) ett
on ett.code = et.code;

另一种方法将使用两个连接:

select e.*
from equipment e join
equipment_type ete
on e.etid = ete.etid and ete.discipline = 'ELEC' join
equipement_type etm
on ete.code = etm.code and etm.discipline = 'MECH';

如果使用正确的索引,此版本可能会更快。

关于mysql - 基于外键的SELECT,更改引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38516590/

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