Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If condition with group_concat in mysql

Tags:

mysql

I have table which has 2 columns empid & depid. This table does not have any primary key. Below is the data of the table.

+-------+-------+
| empid | depid |
+-------+-------+
|     1 |     1 |
|     1 |     2 |
|     1 |     3 |
|     1 |     4 |
|     2 |     1 |
|     2 |     2 |
|     2 |     3 |
|     2 |     4 |
+-------+-------+

Now to select all the depids for an employee I wrote below query.

select empid, group_concat(depid separator ':') from emp group by empid;

It is giving me expected output.

+-------+-----------------------------------+
| empid | group_concat(depid separator ':') |
+-------+-----------------------------------+
|     1 | 1:2:3:4                           |
|     2 | 1:2:3:4                           |
+-------+-----------------------------------+

Now I want select only those depids which are greater than 2. How can I use if with group_concat?

like image 217
GD_Java Avatar asked Jun 19 '15 18:06

GD_Java


People also ask

What does Group_concat do in MySQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.

How to sort GROUP_ CONCAT in MySQL?

Because the GROUP_CONCAT function is an aggregate function, to sort the values, you must use the ORDER BY clause inside the function, not in the ORDER BY in the SELECT statement. The SELECT clause returns one string value so the ORDER BY clause does not take any effect in this statement.


1 Answers

Try as below :

SELECT empid, GROUP_CONCAT(IF(depid > 2, depid, NULL) SEPARATOR ':') 
FROM emp
GROUP BY empid;
like image 147
AnkiiG Avatar answered Sep 30 '22 01:09

AnkiiG