0

有没有更有效的方法来做到这一点?我不想更新多个记录,并且两个初始查询可能会匹配两个不同的记录。

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;
4

2 回答 2

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
于 2012-11-21T20:55:30.183 回答
-1
UPDATE applications SET status = vStatus WHERE appID = @AppID LIMIT 1;
于 2012-11-21T20:13:35.830 回答