2016-07-22 82 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';