我有以下表格:
table1
========
rpid | fname | lname | tu | fu | tu_id | start_time
table2
========
tu_id | tu | fu | start_time
我想使用table2中的匹配记录填充table1' tu,fu和tu_id。我根据时间戳匹配它们。
UPDATE table1
INNER JOIN table1
ON date_trunc('hour', table1.start_time) date_trunc('hour', table2.start_time) AND table1.rpid=table2.tu
SET table1.tu_id= table2.tu_id, table1.fu = table2.fu, table1.tu=table2.tu;
我现在正在收到语法错误:
错误:语法错误在或附近" INNER" 第1行:在date_trunc上更新table1 INNER JOIN table1(' hour',table1.s ...
我以前从未尝试过这样的事情,所以我确定我错过了一些明显的东西。 有什么建议?
我知道INNER JOIN本身是正确的,因为我先在SELECT语句中尝试过它。它返回我想要的数据......现在我只是更新table1中的字段。 谢谢。
编辑1
还试过这个:
UPDATE table1
SET tu_id, fu, tu FROM (
SELECT table2.tu_id, table2.fu, table2.tu
FROM table1, INNER JOIN table1 on date_trunc('hour', table1.start_time) = date_trunc('hour', table2.start_time) AND table1.rpid=table2.tu
);
这给了我语法错误:
ERROR: syntax error at or near ","
LINE 1: UPDATE table1 SET tu_id, fu, tu FROM ( SELECT table2.t...
答案 0 :(得分:1)
UPDATE table1 SET tu_id= table2.tu_id, fu = table2.fu, tu=table2.tu
from table2
where
date_trunc('hour', table1.start_time) = date_trunc('hour', table2.start_time) and table1.rpid=table2.tu
;
答案 1 :(得分:0)
在postgres 9.5(最后一个稳定版本)
之前,您只能使用一个选择更新多个列所以语法如下:
9.5之前:
UPDATE table1
SET tu_id = (SELECT table2.tu_id
FROM table1
INNER JOIN table2
ON date_trunc('hour', table1.start_time) = date_trunc('hour', table2.start_time)
AND table1.rpid=table2.tu),
fu = (SELECT table2.fu
FROM table1
INNER JOIN table2
ON date_trunc('hour', table1.start_time) = date_trunc('hour', table2.start_time)
AND table1.rpid=table2.tu),
tu = (SELECT table2.tu
FROM table1
INNER JOIN table2
ON date_trunc('hour', table1.start_time) = date_trunc('hour', table2.start_time)
AND table1.rpid=table2.tu);
9.5+:
UPDATE table1
SET (tu_id, fu, tu) = (
SELECT table2.tu_id, table2.fu, table2.tu
FROM table1
INNER JOIN table2
ON date_trunc('hour', table1.start_time) = date_trunc('hour', table2.start_time)
AND table1.rpid=table2.tu
);
编辑: 我忘记了UPDATE ... FROM ...,感谢其他回复者在我的记忆中刷新它!
答案 2 :(得分:0)
我相信这是最简单的方法:
UPDATE table1 t
SET tu_id = t2.tu_id,
fu = t2.fu,
tu = t2.tu
FROM table2 t2
WHERE date_trunc('hour', t.start_time) = date_trunc('hour', t2.start_time)
AND t.rpid=t2.tu;