1

更新表“佣金”中的某些行时遇到问题。现在我有像 bar/123/456 这样的commission_number。我想将它重命名为 John/123/456 等,从“用户”表中取一个名字

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”。但不知道如何从“用户”表中放置“用户名”。我只需要替换'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

4 回答 4

3
update commission 
   set commission_number = u.username || '/' || left(commission_number, -strpos(commission_number, '/'))
from users u
  where u.user_id = commission.user_id
于 2013-03-12T13:47:21.707 回答
1

我会从尝试类似的东西开始...

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

除了前 3 个字符之外,还right(commission_number,-3)可以从中获取所有字符。

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

于 2013-03-12T13:39:04.110 回答
1

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

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);
于 2013-03-12T13:48:41.337 回答
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 Fiddle上展示

于 2013-03-12T13:53:30.227 回答