sql - 使用 SQL 更新多对多表

标签 sql sql-server many-to-many

我有一张有动物的 table

CREATE TABLE Animals
(
AnimalId int NOT NULL,
Color int NOT NULL,
Breed int NOT NULL,
Genre int NOT NULL,
);

和一个完全相同的表,但一切都是可选的(除了键)

CREATE TABLE Expenses
(
ExpenseId int NOT NULL,
Color int,
Breed int,
Genre int,
);

最后是一个多对多表:

CREATE TABLE AnimalsExpenses
(
ExpenseId int NOT NULL FOREIGN KEY REFERENCES Expenses(ExpenseId),
AnimalId int NOT NULL FOREIGN KEY REFERENCES Animals(AnimalId),
);

记录 (a, e) 应位于 AnimalsExpenses 表中,如果

((SELECT Color FROM Animals WHERE AnimalId = a) = (SELECT Color FROM Expenses WHERE ExpenseId = e)
OR (NULL) = (SELECT Color FROM Expenses WHERE ExpenseId = e))
AND
((SELECT Breed FROM Animals WHERE AnimalId = a) = (SELECT Breed FROM Expenses WHERE ExpenseId = e)
OR (NULL) = (SELECT Breed FROM Expenses WHERE ExpenseId = e))
AND
((SELECT Genre FROM Animals WHERE AnimalId = a) = (SELECT Genre FROM Expenses WHERE ExpenseId = e)
OR (NULL) = (SELECT Genre FROM Expenses WHERE ExpenseId = e))

...如何更新 AnimalsExpenses 的查询?也就是说:它删除了不应该出现在 n-m 表中的记录,并添加了需要出现的记录

示例:

------ Animals -------------------
 AnimalId  Color  Breed  Genre
----------------------------------
     1      1       1      1
     2      1       1      2
     3      1       2      2

----- Expenses -------------------
 ExpenseId  Color  Breed  Genre
----------------------------------
     1       NULL   NULL   NULL      (applies to every animal)
     2       NULL    2     NULL      (applies to animals of breed 2)
     3         1     2      2        (applies exactly to animal 3)

----- AnimalsExpenses -------------------------------------------
  AnimalId   ExpenseId   Is it ok?
-----------------------------------------------------------------
      1        1         yes, because "expense 1" applies to all
      2        1         yes, because "expense 1" applies to all
      3        1         yes, because "expense 1" applies to all

      1        2         no, breed doesnt match
      2        2         no, breed doesnt match
      3        2         yes, because "expense 2" matches breed with "animal 3"

      1        3         no, breed and genre doesnt match
      2        3         no, breed doesnt match
      3        3         yes, everything matches

最佳答案

为什么不直接截断表然后运行

Insert into AnimalsExpenses
select a.AnimalId
  , e.ExpenseId
  from Animals a
  inner join Expenses e on a.Breed = ISNULL(e.Breed, a.Breed) 
          AND a.Color = ISNULL(e.Color, a.Color) 
          AND a.Genre = ISNULL(e.Genre, a.Genre) 

关于sql - 使用 SQL 更新多对多表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37202226/

相关文章:

mysql - 如何同时对DISTINCT和COUNT进行SQL查询

mysql - SQL 查询不适用于连接

sql - 执行存储过程时显示声明的变量值

SQL:将计数与 Clob 结合使用

sql-server - Pentaho水壶: cannot connect to MS SQL Server Express

sql - 如何在SQL Server数据库中隐藏用户密码

MYSQL多对多关系问题

mysql - 一个帐户有多个具有相同用户属性的好友?如何在 DB 中实现它以及它在 ER 图中的样子

entity-framework-4 - 如何在 Entity Framework 设计器中建立多对多关系

sql - 如何在 SQL CREATE TABLE 中使用常量?