查询不起作用时选择案例

时间:2011-07-13 04:56:40

标签: mysql

我不确定案例如何与mysql一起使用,有人能解释这个查询有什么问题吗?

CASE WHEN SELECT COUNT(*) from websites where website_id = 171 and master = 2 > 0
SELECT timestamp from websites where website_id = 171 and master = 2 
ELSE SELECT NOW() as timestamp

3 个答案:

答案 0 :(得分:2)

查看MySQL Control Flow Functions

CASE ...需要THEN关键字才能运作。

你可能想要:

CASE 
    WHEN (SELECT COUNT(*) from websites where website_id = 171 and master = 2) > 0
      THEN (SELECT timestamp from websites where website_id = 171 and master = 2) 
    ELSE NOW()
END as timestamp

但是,如果只有两种可能性,那么你最好使用IF:

IF((SELECT count(*) from websites where website_id = 171 and master = 2) > 0,  
   (SELECT timestamp from websites where website_id = 171 and master = 2),  
   NOW()) AS TIMESTAMP

或者,您可以使用IFNULL并跳过计数(*)

IFNULL((SELECT timestamp from websites where website_id = 171 and master = 2),
   NOW()) AS TIMESTAMP

答案 1 :(得分:1)

我认为您可以重写您的查询,如:

SELECT COALESCE(timestamp, NOW()) from websites where website_id = 171 and master = 2

答案 2 :(得分:0)

使用嵌入选择获取值时,需要将select包装在括号中。此外,CASE需要使用END关闭 试试这个:

CASE
  WHEN (SELECT COUNT(*) from websites where website_id = 171 and master = 2) > 0
    THEN (SELECT timestamp from websites where website_id = 171 and master = 2)
  ELSE (SELECT NOW())
END as timestamp