我正在使用 SQL Server 并将数据从 Excel 文件导入到我的表中。
我的表包括:
我有不同类型的设备,希望将其拆分到名为 BH_Equipment
的自己的表中,并将其链接到主表 BH_Overview
。
我创建了我的表并创建了约束,但是当数据导入到表中时,我刚刚将设备名称存储在 BH_Overview
表中的“设备”列中,该列与 {{1 }}。
我想知道如何根据 BH_Equipment
表中设备列中的内容更新 equipmentId
列以匹配 BH_Overview
中的 Id
表。
你可以看到我为工厂区和职责完成了外键,这是手动完成的,更新语句只有几个外键要链接,但设备有 BH_Equipment
表中有 291 种类型。< /p>
我尝试了更新和内部联接,但无法理解。抱歉,如果我以一种糟糕的方式解决了这个问题,对 SQL 来说相对较新,所以请说明是否有更简单的方法,或者如果之前有人问过这个问题,请链接并查看。
答案 0 :(得分:0)
首先,您应该让表Equipment
中的列BH_OverView
的内容与表equipment
中的列BH_Equipment
内容之一相匹配
然后通过下面的SQL语句,填充表equipmentId
中对应的BH_OverView
update BH_OverView
set equipmentId = (select id from BH_Equipment
where BH_Equipment.equipment=BH_OverView.Equipment)
验证表equipmentId
中BH_OverView
的内容后,可以通过
Equipment
中的BH_OverView
列
alter table BH_OverView drop column Equipment
我使用的是标准 SQL,它应该在大多数数据库上运行。
根据您的评论
您收到一条错误消息
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
这意味着在您的表 BH_Equipment
中,您还有一个同名的 equipment
。您在表 BH_Equipment
to get this equipment and the number of time they exist, use the following SQL statement
选择设备,count(id) 来自 BH_Equipment 按设备分组 有 count(id)>1
delete one of the repeated rows, then the error message will not exist.
答案 1 :(得分:0)
另一个答案很好,但对于 SQL Server,您可以通过联接更轻松地直接更新:
update o
set equipmentId = e.id
from BH_OverView o
join BH_Equipment e on e.equipment = o.Equipment;
这种粗略的语法也适用于 Postgres、MySQL/MariaDB 和更高版本的 SQLite。