我需要一种方法来定义一个变量来保存MYSQL中表达式的结果,这样我就可以在整个查询中使用该变量。
这样就可以了:
SELECT
IF(VALID,EMPLOYEE_NAME,"NULL") AS NAME, /** <-- Note *VALID*
IF(VALID,ID,"NULL") AS ID, /** <-- And here...
IF(VALID,OCCUPATION,"NULL") AS OCCUPATION, /** <-- And here...
IF((**LONG EXPRESSION**), TRUE, FALSE) AS VALID; /** <-- Taken from here
其中LONG EXPRESSION可能是我需要为IF语句中的每个返回的列放置的非常长的表达式,有很多IF。
我的直觉告诉我,我应该能够像每种程序语言一样:
$var = LONG_EXPRESSION(....);
if($var) {..};
if($var) {..};
if($var) {..};
if($var) {..};
这种方式更合乎逻辑,更不容易出错。易于维护,可读,甚至可能优化。
MYSQL中是否有相应的内容?
那么,为每一行执行定义一个参数?
答案 0 :(得分:1)
您只需要一个子查询:
SELECT IF(VALID,EMPLOYEE_NAME,"NULL") AS NAME, /** <-- Note *VALID*
IF(VALID,ID,"NULL") AS ID, /** <-- And here...
IF(VALID,OCCUPATION,"NULL") AS OCCUPATION,
...,
VALID
from (select t.*, IF((**LONG EXPRESSION**), TRUE, FALSE) AS VALID
from t
) t
答案 1 :(得分:0)
执行此操作的更合适的方法可能是在原始表和带有包含long表达式的OUTER JOIN
子句的子查询之间执行WHERE
。
SELECT IF(b.rowid IS NULL, "NULL", a.employee_name) AS name,
IF(b.rowid IS NULL, "NULL", a.id) AS id,
IF(b.rowid IS NULL, "NULL", a.occupation) AS occupation,
...,
IF(b.rowid IS NULL, 0, 1) AS valid
FROM mytable a
LEFT OUTER JOIN
(SELECT rowid FROM mytable
WHERE **LONG EXPRESSION**) b
ON a.rowid = b.rowid
这假设rowid
是表中的唯一键列。