开发者

WHERE clause IN group_concat

I've got the following query:

SELECT name, GROUP_CONCAT(job SEPARATOR ','),
    count(*) FROM users GROUP BY name ORDER BY name ASC

Is it possible to only concat the job fields that do not contain '', and if so how to? I can't do a WHERE clause, because I still need to ones that don't have a 'job'.

Picture the following table:

+-------+----------+
| name  | job      |
+-------+----------+
| Bob   | doctor   |
| Bob   | teacher  |
| Frank | dentist  |
| Tom   |          |
| Tom   |          |
| Tom   |          |
| Tom   |          |
| Tom   | salesman |
+-------+----------+

The current query would result in:

+--------+---------------------------------+----------+
| name   | GROUP_CONCAT(job SEPARATOR ',') | count(*) |
+--------+---------------------------------+----------+
| Bob    | doctor, teacher                 | 2        |
| Frank  | dentist                         | 1        |
| Tom    | ,,,,salesman                    | 5        |
+--------+---------------------------------+----------+

But I want it to be:

+--------+---------------------------------+----------+
| name   | GROUP_CONCAT(job SEPARATOR ',') | count(*) |
+--------+---------------------------------+----------+
| Bob    | doctor,teacher                  | 2        |
| Frank  | dentist                         | 1        |
| Tom    | salesman                        | 5        |
+--------+---------------------------------+----------+

(Don't mind the logic of this table. It is just a simple example to make things clear)

Reason for this is, I am going to explode() the GROUP_CONCAT(job SEPARATOR 开发者_如何学编程',') in php, and in the actual table, there will easily be 1000 useless ,,'s and this would make the explode function very slow. Thanks,

lordstyx.


I've found a solution: instead of making the job '', I'll just make the field Null, and the query ignores it.


You can also use IF():

SELECT name, GROUP_CONCAT( if(job = '', null, job) SEPARATOR ','),
    count(*) FROM users GROUP BY name ORDER BY name ASC


 SELECT name, GROUP_CONCAT(job SEPARATOR ',') FROM USERS
    WHERE job IS NULL OR job NOT LIKE '%,%'
    GROUP BY name ORDER BY name ASC

However, you might be better advised to string replace the comma to something else and then include all the jobs:

 SELECT name, GROUP_CONCAT(REPLACE(job, ',', ';')) FROM USERS
    GROUP BY name ORDER BY name ASC
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜