问题:(请参阅下面的构建脚本,工作站属于卫星,卫星属于群组)
我正在尝试在工作站所属的组上更改组号时更新Station表的硬件描述符。最终,这将成为一个触发器。但是,我的更新语句正在影响工作站表的所有行,我只是不明白为什么。
下面的Try#1和Try#2都更新了站表中的每一行,而不仅仅是属于组的行(Id = 2)。
(ps。请原谅命名约定,这是我继承的数据库)
尝试#1:
DECLARE @insertedID BIGINT = 2
UPDATE STA SET
HardwareDescriptor = CONVERT(nvarchar(10),G.GroupNum) + '-'
+ CONVERT(nvarchar(10),SAT.SatelliteNum) + '-'
+ CONVERT(nvarchar(10),STA.StationNum)
FROM Station STA
INNER JOIN Satellite SAT ON STA.SatelliteID = SAT.SatelliteID
INNER JOIN [Groups] G ON SAT.GroupID = SAT.GroupID
WHERE G.GroupId = @insertedID
尝试#2:
DECLARE @insertedID BIGINT
SET @insertedID = 2
UPDATE Station SET
HardwareDescriptor = CONVERT(nvarchar(10),STA.GroupNum) + '-'
+ CONVERT(nvarchar(10),STA.SatelliteNum) + '-'
+ CONVERT(nvarchar(10),STA.StationNum)
FROM (SELECT STA.StationId, SAT.SatelliteID, G.GroupId,
STA.StationNum, SAT.SatelliteNum, G.GroupNum
FROM Station STA
INNER JOIN Satellite SAT ON STA.SatelliteID = SAT.SatelliteID
INNER JOIN [Groups] G ON SAT.GroupID = SAT.GroupID
AND G.GroupId = @insertedID) STA
WHERE STA.StationId = Station.StationId
构建脚本:
IF OBJECT_ID('Station') IS NOT NULL
DROP TABLE Station;
GO
IF OBJECT_ID('Satellite') IS NOT NULL
DROP TABLE Satellite;
GO
IF OBJECT_ID('Groups') IS NOT NULL
DROP TABLE Groups;
GO
CREATE TABLE Groups
(
GroupId INT NOT NULL PRIMARY KEY,
GroupNum INT NOT NULL
);
CREATE TABLE Satellite
(
SatelliteId INT NOT NULL PRIMARY KEY,
SatelliteNum INT NOT NULL,
GroupId INT FOREIGN KEY REFERENCES Groups(GroupId)
);
CREATE TABLE Station
(
StationId INT NOT NULL PRIMARY KEY,
HardwareDescriptor NVARCHAR(20),
StationNum INT NOT NULL,
SatelliteId INT FOREIGN KEY REFERENCES Satellite(SatelliteId)
);
INSERT INTO Groups (GroupId, GroupNum) VALUES
(1, 1), (2, 2), (3,3)
INSERT INTO Satellite (SatelliteId, SatelliteNum, GroupId) VALUES
(1, 1, 1), (2, 2, 1), (3, 3, 2), (4, 4, 2);
INSERT INTO Station (StationId, SatelliteId, StationNum) VALUES
(1, 1,1 ), (2, 1, 2), (3,1, 3), (4, 2, 4), (5,2, 5), (6, 3, 6), (7,3, 7), (8,3, 8), (9,3, 9);
答案 0 :(得分:2)
在你第一次尝试这一行时:
INNER JOIN [Groups] G ON SAT.GroupID = SAT.GroupID
应该是
INNER JOIN [Groups] G ON SAT.GroupID = G.GroupID
我认为纠正这种联接应该可以解决问题。第二次尝试在用作源派生表的查询中遇到同样的问题。