在这个Query的帮助下我想要一些null结果

时间:2012-04-04 15:45:48

标签: mysql database mysqli case

查询

SELECT
  CASE
  WHEN `tomato_rating` = 0 THEN 'NULL'
  WHEN `tomato_rating` != 0 THEN `tomato_rating`
  END `tomato_rating`,
  ur.`user_rating`, 
  ABS(tomato_rating - ur.`user_rating`) AS avg_guess_error  
FROM user_rating ur
  LEFT JOIN videos v
    ON ur.vid_id = v.id
WHERE ur.user_id = '1'

查看结果屏幕截图进行验证

enter image description here

结果必需

NULL - 50 NULL
50   - 30 20
65   - 33 32
NULL - 16 NULL

3 个答案:

答案 0 :(得分:2)

如果我理解了您的问题,您希望NULL tomato_rating = 0返回{。}}。

为此,您可以使用NULLIF功能:

SELECT
  NULLIF(`tomato_rating`, 0) AS `tomato_rating`,
  ur.`user_rating`, 
  ABS(NULLIF(`tomato_rating`, 0) - ur.`user_rating`) AS avg_guess_error  
FROM user_rating ur
  LEFT JOIN videos v
    ON ur.vid_id = v.id
WHERE ur.user_id = '1'

答案 1 :(得分:1)

我认为这就是你要找的东西:

SELECT
  IF (`tomato_rating` = 0, 'NULL', `tomato_rating`) as `tomato_rating`,
  ur.`user_rating`,
  IF (`tomato_rating` = 0, 'NULL', ABS(tomato_rating - ur.`user_rating`))
    as avg_guess_error  
FROM user_rating ur
LEFT JOIN videos v ON ur.vid_id = v.id
WHERE ur.user_id = '1'

请注意,您使用的是字符串'NULL',而不是NULL

答案 2 :(得分:0)

这是你要找的吗?

SELECT
CASE
WHEN `tomato_rating` = 0 THEN 'NULL'
WHEN `tomato_rating` != 0 THEN `tomato_rating`
END `tomato_rating`,
ur.`user_rating`, 
CASE
WHEN `tomato_rating` = 0 THEN 'NULL'
WHEN `tomato_rating` != 0 THEN ABS(tomato_rating - ur.`user_rating`) 
END `avg_guess_error`,  
FROM user_rating ur
LEFT JOIN videos v
ON ur.vid_id = v.id
WHERE ur.user_id = '1'