如何从查询中选择不同的值并连接到一列

时间:2013-06-03 13:01:52

标签: php mysql group-concat

我有一张带有category列的表格。除了选择客户端之外,我还想在每一行中选择该类别的可能的值 - 即该子集中所有类别的唯一值。

我的表格如下:

| id | name          | category    |
------------------------------------
| 1  | Test Client   | Retail      |
| 2  | Test Client 2 | Corporate   |
| 3  | Test Client 3 | Retail      |
| 4  | Test Client 4 | Retail      |
| 5  | Test Client 5 | Leisure     |

我认为GROUP_CONCAT可以解决这个问题:

SELECT `client`.*, GROUP_CONCAT(DISTINCT client.category) AS possible_categories
FROM (`client`)
WHERE  `name`  LIKE '%query%'
GROUP BY `client`.`id`

...但它只是给了我那个行的类别,而不是其他类别。

我可以在代码中执行此操作,但它是 O(n)操作,我宁愿节省处理时间。以下是我可以在代码中执行此操作的示例:

return array_unique(array_map(function($client)
{
    return $client->category;
}, $clients));

理想的情况是看到这样的表:

| id | name          | category    | possible_categories     |
---------------------------------------------------------------
| 1  | Test Client   | Retail      | Retail,Corporate,Leisure |
| 2  | Test Client 2 | Corporate   | Retail,Corporate,Leisure |
| 3  | Test Client 3 | Retail      | Retail,Corporate,Leisure |
| 4  | Test Client 4 | Retail      | Retail,Corporate,Leisure |
| 5  | Test Client 5 | Leisure     | Retail,Corporate,Leisure |

3 个答案:

答案 0 :(得分:0)

假设您指的是匹配名称的可能类别: -

SELECT `client`.*, Sub1.possible_categories
FROM (`client`)
CROSS JOIN (SELECT GROUP_CONCAT(DISTINCT client.category) AS possible_categories FROM (`client`) WHERE  `name`  LIKE '%query%') Sub1
WHERE  `name`  LIKE '%query%'

请注意LIKE中的前导通配符可能会使其运行缓慢。

答案 1 :(得分:0)

如果“可能的类别”是指所有类别,那么您需要单独计算它们并将它们添加到:

SELECT `client`.*, cc.possible_categories
FROM `client` cross join 
     (select GROUP_CONCAT(DISTINCT client.category) AS possible_categories
      from `client`
      where `name`  LIKE '%query%'
     ) cc
WHERE  `name`  LIKE '%query%'

答案 2 :(得分:0)

我认为这对你有用:

SELECT id, name, category, (SELECT GROUP_CONCAT(distinct category) FROM Client) AS possible_categories
FROM client

请参阅 demo on SQLFiddle