Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top