繁体   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