我目前在两个数据库上有两个查询。对于给定的user_id,第一个将所有值设置为0,并且秒更新每个用户的等级为1.
UPDATE table_1
JOIN table_2 ON table_1.user_id = table_2.user_id
SET table_1.value = 0,
table_2.total_value = 0
WHERE table_2.user_id = %s AND table_1.user_id =%s
和
UPDATE table_1
JOIN table_2 ON table_1.user_id = table_2.user_id
SET table_1.value = 555,
table_2.total_value =1555
WHERE table_1.rank =1
我想将它们整合在一起,这是可能的吗?
答案 0 :(得分:1)
UPDATE table_1
JOIN table_2 ON table_1.user_id = table_2.user_id
SET table_1.value = case when table_2.user_id = %s AND table_1.user_id =%s
then 0
else table_1.value
end,
table_1.value = case when table_1.rank =1 then 555 else table_1.value end,
table_2.total_value = case when table_2.user_id = %s AND table_1.user_id =%s
then 0
else table_2.total_value
end,
table_2.total_value = case when table_1.rank =1 then 1555 else table_2.total_value end
WHERE
(
table_2.user_id = %s AND table_1.user_id =%s
)
OR table_1.rank =1
答案 1 :(得分:0)
您可以使用CASE
语句设置列上的值。
UPDATE table_1
INNER JOIN table_2
ON table_1.user_id = table_2.user_id
SET table_1.value = CASE WHEN table_2.user_id = %s AND table_1.user_id = %s THEN 0
WHEN table_1.rank = 1 THEN 555
ELSE table_1.value
END,
table_2.total_value = CASE WHEN table_2.user_id = %s AND table_1.user_id = %s THEN 0
WHEN table_1.rank = 1 THEN 1555
ELSE table_1.value
END
WHERE (table_2.user_id = %s AND table_1.user_id = %s) OR
(table_1.rank = 1)