繁体   English   中英

SELECT 来自 Where 子句中的多个 IF 条件

[英]SELECT from Multiple IF conditions in Where Clause

我有以下查询

SELECT *
FROM products a, productImgs b
WHERE a.visible = 1 AND a.Type IN ('Accessories', 'Clothing', 'Electronics')
ORDER BY a.visibleOrder ASC
LIMIT 100

在上面的查询中,我需要添加 IF 条件,即 IF a.Type 是 Accessories 那么我需要从某些 a.Brands 到 select 如果 a.Type 是 Clothing 那么我需要从某些 a.Brands 到 select

For a.Type 'Accessories' ->  a.Brands IN (ALL)
For a.Type 'Clothing'    ->  a.Brands IN ('A','B','C')
For a.Type 'Electronics' ->  a.Brands IN ('D','E','F')

使用CASE表达式,但您还应该为 2 个表编写一个带有ON子句的正确连接:

SELECT * 
FROM products a INNER JOIN productImgs b
ON .....
WHERE a.visible=1 
  AND CASE a.Type 
        WHEN 'Accessories' THEN 1
        WHEN 'Clothing' THEN a.Brands IN ('A','B','C')
        WHEN 'Electronics' THEN a.Brands IN ('D','E','F')
      END 
ORDER BY a.visibleOrder ASC LIMIT 100;

像使用任何其他 where 子句一样使用括号和and/or条件:

where a.visible = 1 and (
  a.Type = 'Accessories' or
  a.Type = 'Clothing'    and a.Brands IN ('A', 'B', 'C') or
  a.Type = 'Electronics' and a.Brands IN ('D', 'E', 'F')
)

这应该给 MySQL 使用索引的机会。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM