我有简单的sql语句:
willTransitionToViewControllers()
我只想在UPDATE people
SET (updated_at, first_name, last_name, email) =
(now(), r.first_name, r.last_name, r.email)
WHERE id = r.p_id;
为email
时设置r.email
值。
有没有办法在一个查询中执行此操作?
答案 0 :(得分:1)
我认为这是另一个查询的一部分
您需要添加条件。根据哪个DBMS(PostgreSQL,MySQL),您将需要不同的解决方案。
您需要 COALESCE 。
COALESCE
函数返回其非空的第一个参数。
UPDATE people
SET (updated_at, first_name, last_name, email) = (now(), r.first_name, r.last_name,
(COALESCE (r.email, people.email))
FROM people, r
WHERE people.id = r.p_id
您需要 IF 条件:
IF (r.email IS NULL, people.email, r.email)
因此,您需要执行的查询应类似于:
UPDATE people
SET (updated_at, first_name, last_name, email) = (now(), r.first_name, r.last_name,
(IF (r.email IS NULL, people.email, r.email))
FROM people, r
WHERE people.id = r.p_id