我是数据库新手,但我遇到了问题:
这里是AAA,BBB,TABLE-1,TABLE-2和TABLE-3表名(表)。
TABLE-1 (A, B) COMPOUND PRIMARY KEY(A,B) AND A IS REFER FROM *AAA(A)* AND B IS REFER FROM *BBB(B)*
1 1
1 2
2 1
TABLE-2 (D, A) D IS PRIME AND A IS REFER FROM *AAA(A)*
1 1
2 2
TABLE-3 (D, B) COMPOUND PRIMARY KEY(D,B) AND B IS REFER FROM *BBB(B)*
1 1
2 2
HERE MEANING OF TABLE-2 AND TABLE-3 IS
(D, A, B)
1 1 1
2 2 2
但问题是第二行A = 2,B = 2与TABLE-1不匹配。
如何实现这一目标?
例如:
I have Airport, Caterer, Meal, Airport_caterer_map, Airport_Meal_Map
Airport (this main configuration table)
id Name
1 aaa
2 bbb
Caterer (this main configuration table)
id Name
1 mmm
2 nnn
Airport_caterer_map (this main configuration table)
airport_id caterer_id
1 1
1 2
2 1
Meal
id Name caterer_id
1 mmm 1
2 nnn 2
Airport_Meal_Map
mail_id airport_id
1 1
1 2
2 1
2 2 -- This row should be wrong.
why is,
1. meal 2 is available in airport 2
2. meal 2 is providing by caterer 2
3. But there is no mapping between caterer 2 and airport 2 in airport_caterer_map table.
答案 0 :(得分:0)
基本上,您的Airport_Meal_Map实际上应该是Airport_Caterer_Meal_Map - 如果您希望数据库帮助进行一致性检查:
CREATE TABLE Airport
(
id INT primary key,
name VARCHAR(30)
);
INSERT INTO Airport VALUES
(1, 'aaa'),
(2, 'bbb');
CREATE TABLE Caterer
(
id INT primary key,
name VARCHAR(30)
);
INSERT INTO Caterer VALUES
(1, 'mmm'),
(2, 'nnn');
CREATE TABLE Airport_Caterer_Map
(
airport_id INT,
caterer_id INT,
PRIMARY KEY (airport_id, caterer_id),
FOREIGN KEY (airport_id) REFERENCES Airport(id),
FOREIGN KEY (caterer_id) REFERENCES Caterer(id)
);
INSERT INTO Airport_Caterer_Map (airport_id, caterer_id) VALUES
(1, 1),
(1, 2),
(2, 1);
-- INSERT INTO Airport_Caterer_Map (airport_id, caterer_id) VALUES
-- (2, 2);
CREATE TABLE Meal
(
id INT,
name VARCHAR(30),
caterer_id INT,
PRIMARY KEY (id, caterer_id),
FOREIGN KEY (caterer_id) REFERENCES Caterer(id)
);
INSERT INTO Meal (id, name, caterer_id) VALUES
(1, 'mmm', 1),
(2, 'nnn', 2);
-- INSERT INTO Meal (id, name, caterer_id) VALUES
-- (1, 'mmm', 2);
-- INSERT INTO Meal (id, name, caterer_id) VALUES
-- (2, 'nnn', 1);
CREATE TABLE Airport_Meal_Map -- actually Airport_Caterer_Meal_Map
(
meal_id INT,
airport_id INT,
caterer_id INT,
PRIMARY KEY (meal_id, airport_id, caterer_id),
FOREIGN KEY (airport_id, caterer_id) REFERENCES Airport_Caterer_Map(airport_id, caterer_id),
FOREIGN KEY (meal_id, caterer_id) REFERENCES Meal(id, caterer_id)
);
INSERT INTO Airport_Meal_Map (meal_id, airport_id, caterer_id) VALUES
(1, 1, 1),
(1, 2, 1),
(2, 1, 2);
-- Fails as meal 1 is not prepared by caterer 2
-- INSERT INTO Airport_Meal_Map (meal_id, airport_id, caterer_id) VALUES
-- (1, 1, 2);
-- Fails as meal 2 is not prepared by caterer 1
-- INSERT INTO Airport_Meal_Map (meal_id, airport_id, caterer_id) VALUES
-- (2, 1, 1);
-- Fails as airport 2 is not served by caterer 2
-- INSERT INTO Airport_Meal_Map (meal_id, airport_id, caterer_id) VALUES
-- (2, 2, 2);