0

我有一个带有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 |
4

3 回答 3

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%'
于 2013-06-03T13:27:10.960 回答
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 中的前导通配符可能会使其运行缓慢。

于 2013-06-03T13:25:42.340 回答
0

我认为这对你有用:

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

请参阅SQLFiddle 上的演示

于 2013-06-03T13:28:32.550 回答