MySql: extracting distinct entries from three different columns of same table
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
精彩评论