Postgres - 更改列数据

时间:2013-03-12 13:23:45

标签: sql postgresql sql-update

更新表'委托'中的某些行时遇到问题。现在我有一个像bar / 123/456这样的Commission_number。我想将它重命名为John / 123/456等,从'user'表中取一个名字

commission                       user
-------------------------        -----------------
commission_number|user_id         username|user_id
-------------------------        -----------------
bar/123/456      | 1               John   | 1
bar/123/123      | 2               Bob    | 2
bar/456/123      | 3               Thomas | 3

以下是我的查询,使用'baz'。但是不知道如何从'user'表中放置'username'。我只需要替换'baz',并使用'user'中的用户名,但不知道如何。

UPDATE commission
SET commission_number = overlay(commission_number placing 'baz' FROM POSITION('bar' IN commission_number) for 3)
WHERE commission_number in (1,2,3,4,5,6,7,8)

4 个答案:

答案 0 :(得分:3)

update commission 
   set commission_number = u.username || '/' || left(commission_number, -strpos(commission_number, '/'))
from users u
  where u.user_id = commission.user_id

答案 1 :(得分:1)

我首先尝试类似......

UPDATE commission
SET commission_number = 
  (SELECT UserName FROM User WHERE user.user_id=commission.user_id)
   ||SubString(commission_number,4,8000)

还有right(commission_number,-3)除了前三个字符之外的所有字符。

我不确定你要做什么 WHERE commission_number in (1,2,3,4,5,6,7,8)

答案 2 :(得分:1)

这说明了更新后数据的外观。当我使用字符串函数时,我经常使用这种select语句。

select c.commission_number, c.user_id, 
       (select username 
        from "user" 
        where "user".user_id = c.user_id) username,
       overlay(c.commission_number 
               placing (select username 
                        from "user" 
                        where "user".user_id = c.user_id) 
               from 1 for 3)
from commission c;

现在,您可以按照您知道可以使用的术语编写更新语句。

update commission 
set commission_number = overlay(commission_number 
                                placing (select username 
                                         from "user" 
                                         where "user".user_id = commission.user_id) 
                                from 1 for 3);

答案 3 :(得分:1)

尝试此查询:

 update commission
 set commission_number=user_table.user_name+
  SUBSTRING(SUBSTRING(commission.commission_number,CHARINDEX('/',commission.commission_number,1)+0,LEN(commission.commission_number))
                ,1
                ,CHARINDEX('/',SUBSTRING(commission.commission_number,CHARINDEX('/',commission.commission_number,1)+1,LEN(commission.commission_number)),1)+LEN(commission.commission_number))
 from commission
 inner join user_table on user_table.user_id=commission.user_id

Sql Fiddle

上验证

花了一些时间在 SQL小提琴

上显示