[英]PostgreSQL multi-table query with name, first_name, and last_name
I have two tables in my PostgreSQL database. 我的PostgreSQL数据库中有两个表。
One table, call it 'Archive', has a column 'name' which are two-word first-name and last-name, eg 'John Smith' and an empty column which wants to be full of 'user_id'. 一个名为“ Archive”的表具有一个名为“ name”的列,该列是两个单词的名字和姓氏,例如“ John Smith”,还有一个空列,希望填充“ user_id”。
The second table, call it 'User Accounts', has three columns, one 'first_name' and one 'last_name' and one 'id'. 第二个表称为“用户帐户”,具有三列,一列为“ first_name”,一列为“ last_name”,一列为“ id”。
My goal is to implement a query that uses the column in Archive to select for the corresponding first_name and last_name in User Accounts and return to Archive the 'id' into 'user_id' column 我的目标是实现一个查询,该查询使用“存档”中的列为用户帐户中的相应first_name和last_name进行选择,然后将“ id”返回到“ user_id”列中进行存档
You can use a join
. 您可以使用join
。 For instance: 例如:
select a.*, ua.id as user_id
from archive a left join
user_accounts ua
on a.name = ua.first_name || ' ' || ua.last_name;
If you actually want to update the column: 如果您实际上要更新列:
update archive a
set user_id = ua.id
from user_accounts ua
where a.name = ua.first_name || ' ' || ua.last_name;
Note that name matching can be quite tricky. 请注意,名称匹配可能非常棘手。 You may not get as many matches as you expect. 您可能不会获得预期的匹配数。 If this turns out to be an issue, ask another question . 如果发现这是一个问题,请问另一个问题 。 Include sample data and desired results in the question. 在问题中包括样本数据和所需结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.