从选择范围更新oracle

时间:2014-11-05 08:16:28

标签: oracle

我使用这个sql

SELECT * 
FROM (
  SELECT a.*, rownum rnum
  FROM (
    SELCT s.id, s.user_id, u.user_id u_id
    FROM sample s
    INNER JOIN template t ON s.t_id = t.t_id
    INNER JOIN user u ON t.u_id = u.u_id
    ORDER BY u.u_id desc
  ) a WHERE rownum <= 100
) WHERE rnum >= 0

sql查询结果

id  user_id  u_id
1   A001     B001
2   A002     B002
3   A003     B003
4   A004     B004
5   A005     B005

我可以使用一个sql for php将user_id更新为u_id的值,而不是使用代码来运行循环,谢谢。

这是我想要的结果:

id  user_id  u_id
1   B001     B001
2   B002     B002
3   B003     B003
4   B004     B004
5   B005     B005

2 个答案:

答案 0 :(得分:2)

是的,非常简单,不考虑复杂的update语句,您可以使用merge ...

merge into sample TGT
using (
  -- your original query starts here
  SELECT * 
  FROM (
    SELECT a.*, rownum rnum
    FROM (
      SELECT s.id, s.user_id, u.user_id u_id
      FROM sample s
      INNER JOIN template t ON s.t_id = t.t_id
      INNER JOIN user u ON t.u_id = u.u_id
      ORDER BY u.u_id desc
    ) a WHERE rownum <= 100
  ) WHERE rnum >= 0
  -- your original query ends here
) SRC
on ( TGT.id = SRC.id )
when matched then
  update set TGT.user_id = SRC.u_id
;

答案 1 :(得分:1)

您想要使用表sample作为来源更新表user吗?

merge into sample s
using (select t.t_id, u.user_id
         from user u, template t
        where u.u_id = t.u_id) u_source
on (u_source.t_id = s.t_id)
when matched then update
set s.user_ud = u_source.user_id