SQL 如何通过特定列将两个表连接在一起?

SQL How to connect two tables together by a specific column?

我有两个 table:大学和 university_list

表 1 - 大学

表 2 - university_list

我在 table 2 中添加了 university_id,我需要连接两个 table。

如果 table 1 中的 university_name 和 table 2 中的 name 相同,则从 table 1 中获取 id 并替换它到 table 2 university_id

提前致谢!

select a.id,b.name from table1 as a
inner join table2 as b
on a.university_name = b.name

以上查询将 return id 和 name of university 如果匹配。在变量中保存值并在更新查询中传递变量。

update table2 set university_id = '$val' where b.name = '$name';

这是一个简单的加入更新 您可以使用以下查询

更新 table 2
update ul
set university_id = u.id
from 
  university u inner join university_list ul on ul.name = u.university_name 

你也可以参考Join Update

UPDATE university_list a 
JOIN university b ON a.name = b.university_name 
SET a.university_id = b.id