2012-10-09 42 views
1
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子句。MySQL的IF子句问题

我可以简单地实现,通过编写

SELECT reportId FROM T_Name where status='EndSP'; 

,但我需要做它用,如果还是如此。

编辑/ UPDATE

我的实际查询看起来像

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; 

回答

1

不能使用只有IF/CASE因为他们不从结果集,当筛选出的值调用IFCASE,结果集已经确定。

+0

那么,有没有其他办法可以做到这一点无覆盖t使用where子句..? –

+1

你可以使用'HAVING'子句,但它会是特殊的。您可以用编程语言筛选结果,并将其接收。或者你可以在主选择上使用select并在那里添加一个WHERE子句。 –

0
SELECT 
reportId as 'reportId_EndSP' 
FROM T_Name where IF(status='EndSP',reportId,' ') LIMIT 10; 
2

如何:

SELECT * FROM (
    SELECT 
     IF(status='EndSP',reportId,'') as reportId_EndSP 
     FROM T_Name) a 
WHERE reportId_EndSP != '' LIMIT 10; 

演示http://sqlfiddle.com/#!2/d1167/8

或单一选择版本

SELECT 
    IF(status='EndSP',reportId,'') as reportId_EndSP 
    FROM T_Name 
HAVING reportId_EndSP != '' LIMIT 10; 

演示http://sqlfiddle.com/#!2/d1167/9

+0

感谢您的回答+1 .....看看我的编辑/更新部分...我得到0行结果集。 –

+0

如果在使用'OR'而不是'AND'的情况下,'status'在同一时间对于单行是不可能等于'EndSP'和'BeginSP'! – xception

+0

简化小提琴http://sqlfiddle.com/#!2/d1167/16,删除我没有的行,并将BeginSP重命名为StartSP - 但它应该证明这一点 – xception