ifnull on subquery返回... NULL

时间:2013-11-27 18:41:02

标签: mysql sql

当我期望NULL 0NULL时,此子查询返回SELECT (SELECT ifnull(visit.timestamp, 0) AS ifnull_1 FROM keyword WHERE visit.keyword_id = keyword.id ORDER BY visit.timestamp DESC LIMIT 1) AS keyword_last_visit FROM keyword LEFT OUTER JOIN visit ON visit.keyword_id = keyword.id 的任何想法:

keyword_last_visit

NULL始终返回{{1}}

2 个答案:

答案 0 :(得分:1)

使用CASE

尝试此操作
SELECT 
(SELECT (CASE WHEN visit.timestamp IS NULL THEN 0 ELSE visit.timestamp END) AS ifnull_1
   FROM keyword
   WHERE visit.keyword_id = keyword.id
   ORDER BY visit.timestamp DESC LIMIT 1) AS keyword_last_visit
FROM keyword
LEFT OUTER JOIN visit ON visit.keyword_id = keyword.id

答案 1 :(得分:0)

这应该用在外部查询..

SELECT
  ifnull((SELECT ifnull(visit.timestamp, 0) AS ifnull_1
   FROM keyword
   WHERE visit.keyword_id = keyword.id
   ORDER BY visit.timestamp DESC LIMIT 1), 0) AS keyword_last_visit
FROM keyword
LEFT OUTER JOIN visit ON visit.keyword_id = keyword.id