WHERE条件下的IF语句

时间:2018-05-17 18:48:21

标签: mysql sql

我有两张相关的表格;类别和订阅。类别>订阅的关系并不总是存在。所以我需要这样的东西:

SELECT * FROM categories
LEFT JOIN subscriptions 
ON subscriptions.category_id = categories.category_id 
WHERE
 IF EXISTS(subscriptions.is_enable)
  categories.type = 'premium' AND
  subscriptions.is_enable = 1
ELSE
  categories.type = 'premium' AND

有没有办法写这样的条件?

2 个答案:

答案 0 :(得分:1)

您可以在逻辑上重写您的条件:

SELECT * FROM categories
LEFT JOIN subscriptions 
ON subscriptions.category_id = categories.category_id 
WHERE (subscriptions.is_enable IS NULL OR subscriptions.is_enable = 1)
  AND categories.type = 'premium'

答案 1 :(得分:0)

由于if / else子句中的所有术语都是逻辑与,因此您可以简单地对它们进行逻辑分组。

SELECT * FROM categories
LEFT JOIN subscriptions 
ON subscriptions.category_id = categories.category_id 
WHERE
  (EXISTS(subscriptions.is_enable) AND 
  categories.type = 'premium' AND
  subscriptions.is_enable = 1)
OR
  (categories.type = 'premium' AND...)