开发者

MySql: extracting distinct entries from three different columns of same table

开发者 https://www.devze.com 2023-03-31 04:42 出处:网络
I have a table called deals which stores client_id1, client_id2, client_id3. These ids correspond to clients table which have clientName and client开发者_StackOverflow_id fields.

I have a table called deals which stores client_id1, client_id2, client_id3.

These ids correspond to clients table which have clientName and client开发者_StackOverflow_id fields.

How can I create a string array of names whose ids are there in any of the three columns of table deals.


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

Explanation:

Get client from one table:

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

The union will get them from the other tables, too

 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)

Now to get a Comma-Seperated-String, either do this clientside (php) or let the MySQL server do it, using a GROUP_CONCAT:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消