簡體   English   中英

將兩列合並為一列

[英]join two columns to one column

我有一個表定義“連接”和另一個定義“設備”

我在連接表中有一個“ 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  

您將需要進行自我加入。嘗試以下查詢:

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兩次。

嘗試這個:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM