0

I have 2 tables: Equipment, and 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       |

So from this example, we can see that both of our equipment are electrical motors.

However, due to a misunderstanding in the initial population, all of the equipment types were identified a ELEC disciplines. Since then, the MECH equipment has been identified, and I have to find all of the equipment that has been duplicated in the Equipment_Type table, and change them to reference the MECH equipment types instead.

I tried this:

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

Which (obviously) returns no results - as with all the other JOIN queries.

What I want to achieve is a search that will select only the Equipment that has an ELEC Equipment Type that is also a MECH equipment type. I realise this requires a nested query, but I'm not sure where to place it.

So the search should return:

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

Because that entry needs to be changed to the MECH discipline (i.e. ETId = 2 instead of 1)

4

2 回答 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';

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

于 2016-07-22T01:10:44.963 回答
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';

如果您想包含“机械”;

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';
于 2016-07-22T01:11:22.810 回答