WHERE 条件下的三进制 (MySQL)?
Ternary in WHERE condition (MySQL)?
MySQL (5.7.x): 有没有在 WHERE 条件下进行三元论证的方法?
我正在尝试 运行 基于 select 的值的 AND 子句:
SELECT DISTINCT p.user_id, eml.template, eml.subject
FROM order_lines ol, email_template eml
JOIN user p ON ol.user_id = p.user_od
WHERE ol.status in (9.2, 10)
-- This line here
AND eml.name = (ol.status = 10 'SurveyOne' ? 'SurveyTwo')
我需要从 eml 中获取 user_id 和基于 ol.status 值的条件行。
在MySQL中,三元运算符是IF()
函数。
AND eml.name = IF(ol.status = 10, 'SurveyOne', 'SurveyTwo')
通常,在 SQL 中,我们尽量将条件逻辑排除在 where
子句之外(它可能比简单逻辑更难理解)。
所以,考虑一下:
WHERE (ol.status = 10 and eml.name = 'SurveyOne') or
(ol.status = 9.2 and eml.name = 'SurveyTwo')
注意:常数“9.2”是可疑的。当你有带小数点的数字并且你正在使用 =
.
进行比较时,你需要非常小心
在某些数据库中(但不是 MySQL),这可以简化为:
WHERE (ol.status, eml.name) in ( (10, 'SurveyOne', (9.2, 'SurveyTwo') )
MySQL (5.7.x): 有没有在 WHERE 条件下进行三元论证的方法?
我正在尝试 运行 基于 select 的值的 AND 子句:
SELECT DISTINCT p.user_id, eml.template, eml.subject
FROM order_lines ol, email_template eml
JOIN user p ON ol.user_id = p.user_od
WHERE ol.status in (9.2, 10)
-- This line here
AND eml.name = (ol.status = 10 'SurveyOne' ? 'SurveyTwo')
我需要从 eml 中获取 user_id 和基于 ol.status 值的条件行。
在MySQL中,三元运算符是IF()
函数。
AND eml.name = IF(ol.status = 10, 'SurveyOne', 'SurveyTwo')
通常,在 SQL 中,我们尽量将条件逻辑排除在 where
子句之外(它可能比简单逻辑更难理解)。
所以,考虑一下:
WHERE (ol.status = 10 and eml.name = 'SurveyOne') or
(ol.status = 9.2 and eml.name = 'SurveyTwo')
注意:常数“9.2”是可疑的。当你有带小数点的数字并且你正在使用 =
.
在某些数据库中(但不是 MySQL),这可以简化为:
WHERE (ol.status, eml.name) in ( (10, 'SurveyOne', (9.2, 'SurveyTwo') )