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 then I need certain a.Brands to select from and if a.Type is Clothing then我需要 select 来自某些 a.Brands
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 有机会使用索引。
我有以下查询
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 then I need certain a.Brands to select from and if a.Type is Clothing then我需要 select 来自某些 a.Brands
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 有机会使用索引。