我有2个表:Equipment
和Equipment_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
设备类型 a MECH
的设备设备类型。我意识到这需要一个嵌套查询,但我不确定在哪里放置它。
所以搜索应该返回:
+---------------------------+
| EqNum | ETId | Discipline |
+---------------------------+
| DEF | 1 | ELEC |
因为该条目需要更改为MECH
学科(即ETId = 2而不是1)
答案 0 :(得分: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';
使用正确的索引,此版本可能会更快。
答案 1 :(得分:0)
这样做:
select eq_id, eq_name,et_id,description from
(select eq_id,eq_name from equipment) as a
left join
(select et_id,description from equipment_type) as b
on a.eq_id = b.et_id where description = 'ELEC';
如果你想包括'MECH';
select eq_id, eq_name,et_id,description from
(select eq_id,eq_name from equipment) as a
left join
(select et_id,description from equipment_type) as b
on a.eq_id = b.et_id where description = 'ELEC' or description = 'MECH';
将'ELEC'改为'MECH':
select eq_id, eq_name,et_id,
case when description = 'ELEC' then 'MECH' else description end as description,
'MECH' as MECH_FIELD from
(select eq_id,eq_name from equipment) as a
left join
(select et_id,description from equipment_type) as b
on a.eq_id = b.et_id where description = 'ELEC' or description = 'MECH';