0

我有三个表,其中一个需要更新:

CREATE TABLE Containers (
  ID int PRIMARY KEY,
  FruitType int
)
CREATE TABLE Contents (
  ContainerID int,
  ContainedFruit int
)
CREATE TABLE Fruit (
  FruitID int,
  Name VARCHAR(16)
)

INSERT INTO Fruit VALUES ( 0, 'Mixed' )
INSERT INTO Fruit VALUES ( 1, 'Apple' )
INSERT INTO Fruit VALUES ( 2, 'Banana' )
INSERT INTO Fruit VALUES ( 3, 'Cherry' )
INSERT INTO Fruit VALUES ( 4, 'Date' )

INSERT INTO Containers VALUES ( 101, 0 )
INSERT INTO Containers VALUES ( 102, 0 )
INSERT INTO Containers VALUES ( 103, 0 )
INSERT INTO Containers VALUES ( 104, 3 )

INSERT INTO Contents VALUES ( 101, 1 )
INSERT INTO Contents VALUES ( 101, 1 )
INSERT INTO Contents VALUES ( 102, 1 )
INSERT INTO Contents VALUES ( 102, 2 )
INSERT INTO Contents VALUES ( 102, 3 )
INSERT INTO Contents VALUES ( 103, 3 )
INSERT INTO Contents VALUES ( 103, 4 )
INSERT INTO Contents VALUES ( 104, 3 )

假设这是我的数据库的状态。请注意,该Fruit表使用了两次。一次描述容器的内容,一次描述容器是否只包含一种水果或是否可以混合。糟糕的设计IMO,但改变它为时已晚。

问题是容器 101 被错误地标记为 MIXED,而实际上它应该是 APPLE。具有多个相同类型内容的容器仍然是同质容器,应该这样标记。

我知道如何进行查询以查找错误标记为混合的容器:

SELECT Contents.ContainerID
FROM Contents
INNER JOIN Containers ON
  Contents.ContainerID = Containers.ID AND
  Containers.FruitType = 0
GROUP BY Contents.ContainerID
HAVING COUNT( DISTINCT Contents.ContainedFruit ) = 1

但是,我不知道如何更新 Container 中发生此错误的每一行。那是我的问题。

4

1 回答 1

0

这将做:

UPDATE Container
SET Container.FruitType = Proper.ProperType
FROM Container
INNER JOIN
(
  SELECT Contents.ContainerID, 
  MAX(Contents.ContainedFruit) ProperType
FROM Contents
INNER JOIN Container ON
  Contents.ContainerID = Container.ID AND
  Container.FruitType = 0
GROUP BY Contents.ContainerID
HAVING COUNT( DISTINCT Contents.ContainedFruit ) = 1
) Proper
ON Container.ID = Proper.ContainerID

SQL小提琴

于 2013-06-18T01:12:25.883 回答