2014-01-10 54 views
2

我定義「連接」一張桌子和另一個定義「設備」加入兩列,一列

我有一個「source_system_name」和連接表'destination_system_name'列。
"system_name",它們在"equipment"表中匹配。

該設備可以是不同類型:

1. Core 
2. Aggregation 
3. Customer. 

我試圖定義一個查詢,以便從設備表中返回的源和目標兩個字段的「類型」。

連接表是這樣的:

id | Source Name | Source port | Destination Name | Destination Port | etc... 
----------------------------------------------------------------------------- 
4 Device_core1 1/1   Device_agg3  3/4 

設備表所示:

id | Equip_name | Equip type | etc.... 
------------------------------------------ 
3 Device_core1 | Core 
7 Device_agg3 | Aggregation 

我想要得到的結果返回,如:

id | Source Name |Source port|Source type|Destination Name|Destination Port|Destination type| 
--------------------------------------------------------------------------------------------- 
1 Device_core1 1/1   Core  Device_agg3  3/4    Aggregation 

查詢我試圖使用的是:

SELECT DISTINCT * FROM connections 
LEFT JOIN equipment on connections.system_name_source=equipment.system_name 
OR connections.system_name_dest=equipment.system_name; 

當我這樣做時,我得到雙記錄,其中Source type字段被Destination type覆蓋,反之亦然。 有沒有可用於查找源和目標數據的equipment表的查詢? 。 即

id | Source Name |Source port|Source type|Destination Name|Destination Port|Destination type| 
1 Device_core1 1/1   Aggregation Device_agg3  3/4    Aggregation 
2 Device_core1 1/1   Core  Device_agg3  3/4    Core 
+0

你應該手動指定字段,然後你就可以設置適當的表和別名 –

回答

2

你需要做自我加入..嘗試此查詢:

SELECT 
connections.id, 
connections.Source_Name, 
connections.Source_port, 
src.systype SourceType, 
connections.Destination_Name, 
connections.Destination_Port, 
tgt.systype DestinationType 
FROM connections 
LEFT JOIN equipment src on connections.system_name_source=src.system_name 
LEFT JOIN equipment tgt on connections.system_name_dest=tgt.system_name 

在上面的查詢,我的別名equipment表格兩次爲srctgt

+0

對不起我的新手。我不明白你在做什麼: 「src.Source_type」和「FROM connections conn」(這個術語的含義是什麼,所以我可以研究這個術語嗎?它幫助我使用實際的表/域名 連接表名是:「connections」列名是「system_name_source 「和」system_name_dest「。設備表名是」equipment「,列名是」system_name「和」systype「。謝謝你的輸入 – Nigel

+0

@Nigel我已經根據你提供的列名更新了上述查詢 – hashbrown

+1

Thanks - 這很有用:感興趣。我現在不能在使用別名時使用原始表名,但需要使用其中一個別名 – Nigel

1

試試這個:

SELECT c.id, c.sourceName, c.sourcePort, 
     MAX(IF(c.sourceName = e.Equip_name, e.equipType, '')) sourceType, 
     c.destinationName, c.destinationPort, 
     MAX(IF(c.destinationName = e.Equip_name, e.equipType, '')) destinationType 
FROM `connection` c 
LEFT JOIN equipment e ON e.Equip_name IN (c.sourceName, c.destinationName) 
GROUP BY c.id; 
+0

嗨,謝謝你的輸入。我是新手。你能解釋一下你在做什麼以及它是如何工作的。 – Nigel

+0

@Nigel我已經將連接表和設備表與設備表的Equip_name加入到連接表的源和目標名稱中。然後根據源名稱和目標名稱獲取類型 –

+0

謝謝 - 此工程也很好。我可能會選擇「僅限Hashbrowns解決方案,因爲它對我來說更容易理解:) – Nigel