2012-04-04 88 views
2

查詢一些空的結果我想和這個查詢的幫助

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 
+0

原諒我,但最新你的問題?你有一個SQL語句和輸出..你有錯誤嗎? – BugFinder 2012-04-04 15:48:04

+0

爲什麼你的最後一列應該是空的?因爲'user_rating'與'tomato_rating'不匹配? – 2012-04-04 15:51:22

回答

1

我認爲這是你在找什麼:你正在使用,而不是NULL'NULL'

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' 

通知。

+0

Thanx分享你的經驗與我(真棒)@Mosty Mostacho – 2012-04-04 15:58:50

2

如果我理解你的問題,如果想返回。

要做到這一點,你可以使用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' 
+0

嗯,不知道'NULLIF'和'IFNULL'。 – talereader 2012-04-04 15:53:50

+0

@telereader注意原始查詢中沒有空值。這是字符串「NULL」什麼是返回 – 2012-04-04 15:55:55

+0

Thanx分享你的經驗與我(真棒@邁克爾Ferdrickson我致敬你的經驗) – 2012-04-04 15:56:05

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'