3

这是我的 MySQL 查询,我在这个查询中有一周的问题。我不知道如何将 IF 条件与WHERE子句一起应用。

询问:

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;

我在这个查询中做错了什么?

4

3 回答 3

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;
于 2012-05-21T08:29:58.393 回答
1

使用CASE WHEN THEN ELSE END结构。您可以在文档中阅读有关它更多信息。

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;
于 2012-05-21T08:27:51.023 回答
1

好吧,看起来您通过这些比较 x 和 x IF

x = x “总是”为真。

于 2012-05-21T08:27:39.207 回答