mysql> SELECT
-> IF(status='EndSP',reportId,'') as 'reportId_EndSP'
-> FROM T_Name LIMIT 10;
+--------------+
| reportId_EndSP |
+--------------+
| |
| |
| 270241 |
| |
| 270242 |
| |
| |
| 270244 |
| |
| |
+--------------+
10 rows in set (0.00 sec)
But i need to return only the row where status = 'EndSP'
我不需要执行else子句。
我可以通过写
来实现这一点SELECT reportId FROM T_Name where status='EndSP';
但我需要使用if或case。
修改/更新
我的实际查询类似于
SELECT
-> IF(status='EndSP',reportId,'') as 'reportId_EndSP',
-> IF(status='EndSP',createdTS,'') as 'createdTS_EndSP',
-> IF(status='BeginSP',reportId,'') as 'reportId_BeginSP',
-> IF(status='BeginSP',createdTS,'') as 'createdTS_BeginSP'
-> FROM T_Name HAVING reportId_EndSP!='' AND reportId_BeginSP!='' LIMIT 10;
答案 0 :(得分:2)
怎么样:
SELECT * FROM (
SELECT
IF(status='EndSP',reportId,'') as reportId_EndSP
FROM T_Name) a
WHERE reportId_EndSP != '' LIMIT 10;
demo http://sqlfiddle.com/#!2/d1167/8
或单一选择版本
SELECT
IF(status='EndSP',reportId,'') as reportId_EndSP
FROM T_Name
HAVING reportId_EndSP != '' LIMIT 10;
答案 1 :(得分:1)
您不能仅使用 IF
/ CASE
,因为当IF
或{{CASE
时,它们不会过滤掉结果集中的值调用1}},结果集已经确定。
答案 2 :(得分:0)
SELECT
reportId as 'reportId_EndSP'
FROM T_Name where IF(status='EndSP',reportId,' ') LIMIT 10;