[英]What is the best SQL query to populate an existing column on table A with a similar column from table B?
Let's say I have an existing table A with a column called contact_name and a ID column id as the primary key.假设我有一个现有的表A ,其中包含一个名为contact_name的列和一个 ID 列id作为主键。 All the rows in A have the name value as "NULL" right now. A中的所有行现在的名称值为“NULL”。
Another table B has different columns, but one of which is contact_name , and another is ref_id .另一个表B有不同的列,但其中一个是contact_name ,另一个是ref_id 。 Each ref_id in B corresponds to a value of id in A , and there may be multiple rows in B that share the same value for ref_id (meaning they all correspond to a single entry in A ). B中的每个ref_id对应于A中的一个id值,并且B中可能有多行共享相同的ref_id值(意味着它们都对应于A中的单个条目)。
Let me set up an example:让我举个例子:
Table A表A
id | contact_name
1 | [NULL]
2 | [NULL]
Table B表B
ref_id | contact_name
1 | "John"
2 | "Helen"
2 | "Alex"
Note there are theoretically other values in each table but for the sake of brevity I'm just showing the values I'm interested in using.请注意,理论上每个表中还有其他值,但为了简洁起见,我只显示我有兴趣使用的值。
I want to populate contact_name in table A with the first entry of the corresponding contact_name in B , where B. (first) ref_id = A.id , without adding any rows or editing the rest of the rows in either table.我想用B中相应的contact_name的第一个条目填充表A中的contact_name ,其中B. (first) ref_id = A.id ,而不添加任何行或编辑任一表中行的 rest。 That is, I want A in my example to now be:也就是说,我希望示例中的 A现在是:
id | contact_name
1 | "John"
2 | "Helen"
Again, note how the first contact_name value, "Helen", in B is selected, not any other subsequent one, like "Alex".再次注意如何选择B中的第一个contact_name值“Helen”,而不是任何其他后续值,如“Alex”。
The MERGE function is made for this. MERGE function 就是为此而制作的。 Give it a try:试一试:
MERGE INTO TABLEA a USING (
SELECT b.REF_ID, b.CONTACT_NAME
FROM TABLEB) b
ON (a.ID = b.REF_ID)
WHEN MATCHED THEN
UPDATE SET
a.CONTACT_NAME = b.CONTACT_NAME
WHERE a.CONTACT_NAME IS null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.