这可能不会直接回答您的问题,而只是一个建议:D
首先,表上的行pizza_topping
不需要用逗号分隔值。使用当前设计很难搜索这样的值。这些值应该存储在行中而不是列中。
考虑以下模式,
CREATE TABLE PIZZA
(
PizzaID INT PRIMARY KEY,
NAME VARCHAR(50) UNIQUE,
PRICE DECIMAL(10,2)
);
INSERT INTO PIZZA VALUES (1,'Sunny Side Up Pizza', 120);
INSERT INTO PIZZA VALUES (2,'BBQ Chicken Pizza', 200);
INSERT INTO PIZZA VALUES (3,'Muffuletta Pizza', 175);
INSERT INTO PIZZA VALUES (4,'Caramelized Onion Pizza', 135);
INSERT INTO PIZZA VALUES (5,'Broccoli Deep Dish Pizza', 150);
CREATE TABLE TOPPINGS
(
ToppingID INT PRIMARY KEY,
NAME VARCHAR(50) UNIQUE
);
INSERT INTO TOPPINGS VALUES (1,'Pepperoni');
INSERT INTO TOPPINGS VALUES (2,'Mushroom');
INSERT INTO TOPPINGS VALUES (3,'Sausage');
INSERT INTO TOPPINGS VALUES (4,'Cheese');
INSERT INTO TOPPINGS VALUES (5,'Garlic');
INSERT INTO TOPPINGS VALUES (6,'Ham');
INSERT INTO TOPPINGS VALUES (7,'Tomato Sauce');
并且每个的记录PIZZA_TOPPING
应该有多行。ToppingID
PizzaID
CREATE TABLE PIZZA_TOPPINGS
(
PizzaID INT,
ToppingID INT,
CONSTRAINT tb_fk1 FOREIGN KEY (PizzaID)
REFERENCES Pizza(PizzaID),
CONSTRAINT tb_fk2 FOREIGN KEY (ToppingID)
REFERENCES TOPPINGS(ToppingID),
CONSTRAINT tb_UQ UNIQUE (PizzaID, ToppingID)
);
INSERT INTO PIZZA_TOPPINGS VALUES (1,1);
INSERT INTO PIZZA_TOPPINGS VALUES (1,2);
INSERT INTO PIZZA_TOPPINGS VALUES (1,3);
INSERT INTO PIZZA_TOPPINGS VALUES (2,4);
INSERT INTO PIZZA_TOPPINGS VALUES (2,5);
INSERT INTO PIZZA_TOPPINGS VALUES (2,6);
INSERT INTO PIZZA_TOPPINGS VALUES (2,7);
INSERT INTO PIZZA_TOPPINGS VALUES (3,1);
INSERT INTO PIZZA_TOPPINGS VALUES (3,3);
INSERT INTO PIZZA_TOPPINGS VALUES (3,5);
INSERT INTO PIZZA_TOPPINGS VALUES (4,2);
INSERT INTO PIZZA_TOPPINGS VALUES (5,1);
INSERT INTO PIZZA_TOPPINGS VALUES (6,7);
INSERT INTO PIZZA_TOPPINGS VALUES (6,1);
这种搜索记录的技术称为关系除法
例如,您想搜索具有以下成分的比萨饼:Pepperoni
、Mushroom
、Sausage
。
SELECT a.PIZZAID, a.NAME, a.PRICE
FROM Pizza a
INNER JOIN Pizza_Toppings b
ON a.PizzaID = b.PizzaID
INNER JOIN Toppings c
ON b.ToppingID = c.ToppingID
WHERE c.Name IN ('Pepperoni', 'Mushroom', 'Sausage')
GROUP BY a.PIZZAID, a.NAME, a.PRICE
HAVING COUNT(*) = 3
或至少包含以下内容的比萨饼:Pepperoni
, Mushroom
,
SELECT a.PIZZAID, a.NAME, a.PRICE
FROM Pizza a
INNER JOIN Pizza_Toppings b
ON a.PizzaID = b.PizzaID
INNER JOIN Toppings c
ON b.ToppingID = c.ToppingID
WHERE c.Name IN ('Pepperoni', 'Mushroom')
GROUP BY a.PIZZAID, a.NAME, a.PRICE
HAVING COUNT(*) = 2
论文比使用任何其他函数(如FIND_IN_SET
,REGEXP
等)要好得多。