Mysql WHERE使用AND&案例条件

时间:2014-09-08 20:13:06

标签: mysql case where

我想添加我的过程中给定平台变量不为空的位置。

- 编辑 -

好的,这是一个程序。程序根据用户的选择过滤结果。 (平台选择)

因此在过程中声明了platform变量。如果用户向过程发送任何平台ID,则必须使用平台变量过滤结果。但是,如果platform变量为null或未定义,则获取所有结果。

注意:我想找到一种在CASE语句中包含多个平台ID的方法

您可以在下面找到完整的代码。

- /编辑 -

(
SELECT gn.title, gn.slug, gn.created_at, gn.content, gi.image, 'news' as `type` FROM `game_news` gn 
CROSS JOIN `gallery_images` gi ON gi.foreign_key = gn.id
CROSS JOIN `game_platforms` gp
LEFT JOIN `game_news_platform_relation` gnpr ON gnpr.news_id = gn.`id` 
WHERE gi.gallery_id = 7 AND gi.is_main = '1' AND `gi`.`thumbnail_id` = 16 AND gn.deleted_at IS NULL AND gi.deleted_at IS NULL
AND (
    CASE 
        WHEN platform is NOT NULL 
            THEN gnpr.platform_id IN(platform)
    END
    )
GROUP BY gn.id
)
UNION ALL
(
SELECT gr.title, gr.slug, gr.created_at, gr.content, gi.image, 'review' as `type` FROM `game_reviews` gr 
CROSS JOIN `gallery_images` gi ON gi.foreign_key = gr.id
CROSS JOIN `game_platforms` gp
LEFT JOIN `game_review_platform_relation` grpr ON grpr.review_id = gr.`id` 
WHERE gi.gallery_id = 6 AND gi.is_main = '1' AND `gi`.`thumbnail_id` = 14 AND gr.deleted_at IS NULL AND gi.deleted_at IS NULL
AND (
    CASE 
        WHEN platform is NOT NULL 
            THEN grpr.platform_id IN(platform) 
    END
    )
GROUP BY gr.id
)
ORDER BY created_at DESC
LIMIT post_offset, post_limit

我该怎么做?

2 个答案:

答案 0 :(得分:1)

要在案例中使用IN(),它必须在WHEN部分,这样你就可以这样做。

AND
(   CASE
      WHEN platform IS NOT NULL AND gnpr.platform_id IN(platform)
      THEN gnpr.platform_id
      ELSE 1
    END
)

你还可以添加另一个WHEN来吸引这样的一切。

AND
(   CASE
      WHEN platform IS NOT NULL AND gnpr.platform_id IN(platform)
      THEN gnpr.platform_id
      WHEN platform IS NULL
      THEN gnpr.platform_id
    END
)

答案 1 :(得分:0)

为什么不使用where子句上的case,而是使用从表到平台的LEFT JOIN。然后在where子句上评估platform.ID是否为null。希望这个想法可以帮到你。

修改

如果要在WHERE子句中使用CASE,则需要将其转换为布尔值。像这样:

SELECT p FROM Table WHERE (CASE WHEN Machine ='myMachine' THEN 1 ELSE 0 END) = 1