MySql:从同一张表的三个不同列中提取不同的条目
Posted
技术标签:
【中文标题】MySql:从同一张表的三个不同列中提取不同的条目【英文标题】:MySql: extracting distinct entries from three different columns of same table 【发布时间】:2011-11-05 19:30:04 【问题描述】:我有一个名为deals
的表,其中存储了client_id1
、client_id2
、client_id3
。
这些 id 对应于具有 clientName
和 client_id
字段的 clients
表。
如何创建一个名称的字符串数组,其 id 存在于表交易的三列中的任何一列中。
【问题讨论】:
你或许应该考虑规范化你的数据。 【参考方案1】: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)
现在要获取逗号分隔字符串,要么执行此客户端 (php),要么让 mysql 服务器执行此操作,使用 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
【讨论】:
以上是关于MySql:从同一张表的三个不同列中提取不同的条目的主要内容,如果未能解决你的问题,请参考以下文章