mysql> select * from categories ;
+-------------+--------------------+-----------------+---------------------
| category_id | T1 | T2 | T3
+-------------+--------------------+-----------------+---------------------
| 2 | Popcorn | Bucket | NULL
| 3 | Popcorn | Jumbo | NULL
| 3 | Popcorn | Jumbo | NULL
6 | Popcorn | Combo Relish | NULL |
7 | Soft Drinks | Fountain | Apple |
7 | Soft Drinks | Fountain | Apple |
8 | Soft Drinks | Fountain | Orange |
8 | Soft Drinks | Bottled | Orange |
我有一个名为类别的表格,如上所示。
对于某些T2值,T3可以为空或可以具有值。
我有一个查询,如下所示
select t1, t2,
group_concat(concat(t3,'(',category_id,')')) consildated_Data
from categories
group by 1,2;
这样结果就像这样
Popcorn | Bucket | NULL
Popcorn | Combo Relish | NULL
Popcorn | Jumbo | NULL
Soft Drinks | Fountain | Apple(7),Apple(7),Orange(8)
Soft Drinks | Bottled | Orange(8)
我的问题是,如果T3是null
,我可以将值打印为空,并带有相应的category_id
数字吗?
所以它为Bucket
这样就像这样Popcorn | Bucket | empty(2)
Popcorn | Jumbo | empty(3),empty(3)
是否可以在上述查询中添加if条件??
答案 0 :(得分:3)
在mysql中使用ifnull(x, [defalt_value])
select t1, t2,
group_concat(concat(ifnull(t3, ''),'(',category_id,')')) consildated_Data
from categories
group by 1,2;
或者您也可以使用CASE statment
,但这是一种更加丑陋的方法:
select t1, t2,
group_concat(concat(case t3 when null then '' else t3 end)),'(',category_id,')')) consildated_Data
from categories
group by 1,2;
答案 1 :(得分:2)
如果不进行测试,您可以像这样使用IF statement:
SELECT
t1,
t2,
IF(
t3 IS NULL, -- condition
CONCAT('empty(', category_id, ')'), -- true reaction
GROUP_CONCAT(CONCAT(t3,'(',category_id,')')) -- false reaction
) AS consildated_Data
FROM categories
GROUP BY 1, 2;
答案 2 :(得分:-2)