MySql:从同一个表的三个不同列中提取不同的条目

时间:2011-08-29 06:31:22

标签: mysql join distinct

我有一个名为deals的表,其中存储了client_id1client_id2client_id3

这些ID对应clients表,其中包含clientNameclient_id字段。

如何在表格交易的三列中的任何一列中创建其ID为其的名称的字符串数组。

1 个答案:

答案 0 :(得分:0)

SELECT GROUP_CONCAT(Client) FROM (
 SELECT clientName as Client 
 FROM deals JOIN clients
 ON deals.client_id1 = clients.client_id
UNION ALL
 SELECT clientName as Client 
 FROM deals JOIN clients
 ON deals.client_id2 = clients.client_id
UNION ALL
 SELECT clientName as Client 
 FROM deals JOIN clients
 ON deals.client_id3 = clients.client_id)
GROUP BY Client

说明:

从一个表中获取客户端:

 SELECT clientName as Client 
 FROM deals JOIN clients
 ON deals.client_id1 = clients.client_id

联盟也会从其他表中获取它们

 SELECT clientName as Client 
 FROM deals JOIN clients
 ON deals.client_id1 = clients.client_id
UNION ALL
 SELECT clientName as Client 
 FROM deals JOIN clients
 ON deals.client_id2 = clients.client_id
UNION ALL
 SELECT clientName as Client 
 FROM deals JOIN clients
 ON deals.client_id3 = clients.client_id)

现在要获得一个Comma-Seperated-String,要么使用GROUP_CONCAT来执行此客户端(php)或让MySQL服务器执行此操作:

SELECT GROUP_CONCAT(Client) FROM (
 SELECT clientName as Client 
 FROM deals JOIN clients
 ON deals.client_id1 = clients.client_id
UNION ALL
 SELECT clientName as Client 
 FROM deals JOIN clients
 ON deals.client_id2 = clients.client_id
UNION ALL
 SELECT clientName as Client 
 FROM deals JOIN clients
 ON deals.client_id3 = clients.client_id)
GROUP BY Client