仅基于可能返回多个结果的“or”子句更新一行

时间:2012-11-21 20:12:54

标签: mysql

有更有效的方法吗?我不想更新多个记录,两个初始查询可能匹配两个不同的记录。

SET @AppID = (SELECT appID FROM employees WHERE ssn = vSSN);

IF @AppID IS NULL THEN
    SET @AppID = (SELECT appID from applications WHERE appDate = vDate);
END IF;

UPDATE applications
SET status = vStatus
WHERE appID = @AppID;

2 个答案:

答案 0 :(得分:1)

您可以使用COALESCE运算符和UPDATE / REPLACE语句。更准确地说,COALESCE从逗号分隔列表中选择第一个非空值。

http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_coalesce

http://dev.mysql.com/doc/refman/5.5/en/update.html

http://dev.mysql.com/doc/refman/5.5/en/replace.html

首先,更新UPDATE:

UPDATE applications AS app
INNER JOIN (
SELECT COALESCE(employees.appID, applications.appID) AS appID
FROM applications
LEFT OUTER JOIN employees
ON employees.ssn = vSSN
WHERE applications.appDate = vDate
-- do some ordering or filtering if the date is not unique 
LIMIT 1) AS app2
ON app.appID = app2.appID
SET app.status = vStatus

第二,REPLACE替代方案。请注意,REPLACE首先删除旧条目,然后重新插入新条目。因此,employees.appID可能不是applications.appID的外键。

REPLACE INTO applications (appID, status)
SELECT COALESCE(employees.appID, app2.appID) AS appIdToModify, vStatus
FROM applications AS app2
LEFT OUTER JOIN employees
ON ssn = vSSN
WHERE app2.appDate = vDate

答案 1 :(得分:-1)

UPDATE applications SET status = vStatus WHERE appID = @AppID LIMIT 1;