简体   繁体   中英

If condition with group_concat in 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?

Try as below :

SELECT empid, GROUP_CONCAT(IF(depid > 2, depid, NULL) SEPARATOR ':') 
FROM emp
GROUP BY empid;
select empid, group_concat(depid separator ':') 
from emp 
where depid > 2
group by empid

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