我有两张表格如下:
表A
k | 1 | 2
--------------------
a | mango | xx
b | orange| xx
c | xx | apple
d | xx | banana
a | xx | mango
表B
k | 1 | 2
--------------------
a | |
b | |
c | |
d | |
如何从tableb
更新tablea
,以便我得到以下结果?
表B
k | 1 | 2
--------------------
a | mango | mango
b | orange| xx
c | xx | apple
d | xx | banana
如果我尝试使用如下所示的更新语句
update tableb
set 1 = x.1,
2 = x.2
from
(
select * from tablea
) x
where tablea.k = x.k
如果xx
重复,我可以使更新语句忽略k
吗?
感谢。
答案 0 :(得分:1)
这是SELECT,希望你能进行更新。
<强> SQL Fiddle Demo 强>
SELECT t1."k", t1."1", COALESCE(t2."2", 'xx') "2"
FROM tablea t1
LEFT JOIN tablea t2
ON t1."1" = t2."2"
WHERE t1."1" <> 'xx'
UNION ALL
SELECT t1."k", t1."1", t1."2"
FROM tablea t1
WHERE t1."1" = 'xx'
AND t1."2" NOT IN (SELECT t2."1" FROM tablea t2 WHERE t2."1" <> 'xx')