2012-05-21 64 views
3

這是我的MySQL查詢,我在此查詢中有問題。我不知道如何應用IF條件與WHERE條款。如何在此查詢中使用WHERE CLAUSE IF條件使用MySql

查詢:

SELECT 
*, 
IFNULL((SELECT ur.user_rating FROM user_rating ur 
WHERE ur.vid_id = v.id AND ur.user_id = '1000'),'NULL') AS user_rating 
FROM videos v 
WHERE WEEK(v.video_released_date) = WEEK(NOW()) 
AND 
v.`is_done` = 1 
ORDER BY v.admin_listing ASC; 

我想OR(我如何應用此條件與where子句?)

IF(WEEK(v.video_released_date) = WEEK(NOW()) , WEEK(NOW()) , WEEK(NOW())-1) 
= 
IF(WEEK(v.video_released_date) = WEEK(NOW()) , WEEK(NOW()) , WEEK(NOW())-1) 

簡報

如果視頻發佈日期已過,而不是匹配本週然後上週申請

我自己

當我嘗試自己喜歡這一點,他們還給我整個數據

SELECT 
*, 
IFNULL((SELECT ur.user_rating FROM user_rating ur 
WHERE ur.vid_id = v.id AND ur.user_id = '1000'),'NULL') AS user_rating 
FROM videos v 
WHERE IF(WEEK(v.video_released_date) = WEEK(NOW()),WEEK(NOW()),WEEK(NOW())-1) 
= IF(WEEK(v.video_released_date) = WEEK(NOW()),WEEK(NOW()),WEEK(NOW())-1) 
AND 
v.`is_done` = 1 
ORDER BY v.admin_listing ASC; 

我是什麼在此查詢做錯了什麼?

回答

5

試試這個 -

SELECT *, 
      IFNULL((SELECT ur.user_rating FROM user_rating ur 
        WHERE ur.vid_id = v.id AND ur.user_id = '1000'),'NULL') AS user_rating 
    FROM videos v 
    WHERE WEEK(v.video_released_date) = IF(WEEK(v.video_released_date) = WEEK(NOW()),WEEK(NOW()),WEEK(NOW())-1) 
    AND v.is_done = 1 
    ORDER BY v.admin_listing ASC; 
1

那麼它看起來像你通過這些IF比較x與x。

x = x總是「真」。

1

使用CASE當然後結束構造。您可以在文檔中閱讀更多關於here的文章。

SELECT *, 
    IFNULL((SELECT ur.user_rating FROM user_rating ur 
     WHERE ur.vid_id = v.id AND ur.user_id = '1000'),'NULL') AS user_rating 
    FROM videos v 
    WHERE 
     WEEK(v.video_released_date) = 
      CASE WHEN WEEK(v.video_released_date) = WEEK(NOW()) 
      THEN WEEK(NOW()) ELSE WEEK(NOW())-1 END 
    AND 
     v.`is_done` = 1 
ORDER BY v.admin_listing ASC;