Query relating to split_part() in PostgreSQL

huangapple go评论49阅读模式
英文:

Query relating to split_part() in PostgreSQL

问题

我有一个包含first_name(名字),last_name(姓氏)和name(姓名)的表格。Name(姓名)包含了完整的姓名,例如"Joe Bloggs"。我想要更新表格中的每一行,将first_name(名字)和last_name(姓氏)从name(姓名)列中提取出来,但是我找不到正确的update和子查询组合来使其工作。

我尝试过使用以下代码:

update users a set a.first_name = subquery.first_name_new
from (select username, split_part(name, ' ',1) as first_name_new from users) as subquery
where a.username = subquery.username

我能理解为什么这不起作用,但是我就是找不到正确的组合。

英文:

I have a table with first_name, last_name and name. Name consists of a full name such as "Joe Bloggs". I want to update every row in the table with first_name and last_name derived from the name column, but I just cant find the right combination of update with subquery to make it work.

I have tried using:

update users a set a.first_name = subquery.first_name_new
from (select username, split_part(name, ' ',1) as first_name_new from users) as subquery
where a.username = subquery.username

I can see why this isn't working, but I just cant find the right combination.

答案1

得分: 1

你可以按照以下方式进行:

更新用户
设置 first_name = split_part(name, ' ', 1),
     last_name = split_part(name, ' ', -1)

示例在此处

英文:

You can do it as follows :

update users
set first_name = split_part(name, ' ',1),
     last_name = split_part(name, ' ',-1)

Demo here

答案2

得分: 0

update users
set first_name = split_part(name, ' ', 1),
     last_name = split_part(name, ' ', -1)
英文:
update users
set first_name = split_part(name, ' ', 1),
     last_name = split_part(name, ' ', -1)

huangapple
  • 本文由 发表于 2023年6月13日 02:28:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76459362.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定