2016-07-22 75 views
0

我有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设备类型是一个MECH设备类型的设备进行搜索。我意识到这需要一个嵌套的查询,但我不知道在哪里放置它。

所以搜索应返回:

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

因为该条目需要改变到MECH学科(的即ETID = 2而不是1)

回答

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

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

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

CHANGE 'ELEC' TO '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';