简体   繁体   中英

How to select distinct values from query and concatenate into one column

I've got a table with a category column. Along with the selection of the clients, I'd like to select on each row the possible values of the category - that is, all the unique values of category in that subset.

My table looks like this:

| 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     |

I thought GROUP_CONCAT would do the trick:

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

...but it just gives me that row's category, not the others.

I can do it in code, but it's an O(n) operation and I'd rather save on the processing time. Here's how I could do it in code, for illustrative purposes:

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

The ideal scenario would be to see a table like this:

| 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 |

Assuming you mean the possible categories for the matching names:-

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%'

Note the leading wildcard in the LIKEs will probably make it run slowly.

If by "possible categories" you mean all categories, then you need to calculate them separately and add them in:

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%'

I think this would work for you:

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

See the demo on SQLFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM