简体   繁体   English

如果在mysql中使用group_concat条件

[英]If condition with group_concat in mysql

I have table which has 2 columns empid & depid. 我有一个表有2列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. 现在选择我在下面查询的员工的所有depids。

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? 现在我想只选择那些大于2的depids。如何使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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