我需要MySQL中的查询帮助。
我有2个表,一个名为cars
,一个名为accessories
(这是虚构的)。
cars
表中的一辆车带有一套附件。
车桌看起来像这样。
ID
Name
Accessory 1
Accessory 2
Accessory 3
Accessory 4
Accessory 5
etc..
然后,我希望用户通过复选框指定他想要的配件。
然后运行查询以显示来自cars
的各种车辆,仅 。
ID = 1
Name = Ford Mondeo
Accessory 1 = AC
Accessory 2 = Turbo
ID = 2
Name = Ford Mondeo SE
Accessory 1 = AC
Accessory 2 = Turbo
Accessory 3 = Cruise control
Accessory 4 = CD
ID = 3
Name = Ford Mustang
Accessory 1 = AC
Accessory 2 = Turbo
Accessory 3 = Cruise control
Accessory 4 = CD
Accessory 5 = DVD
如果用户指定了AC
,Turbo
,Cruise control
和CD
,那么第一辆和第二辆车应该显示,但不是第三辆,因为他们没有勾选DVD
。
结果不应显示任何没有“勾选”的帖子。
我希望有人可以帮我构建此操作的查询。
答案 0 :(得分:1)
首先,正如其他人所建议的那样,你应该有一张汽车用的桌子,一张用于配件的桌子,以及一张用于列出每辆汽车配件的链接表。举个简单的例子,您可以像这样设置表格:
CREATE TABLE cars (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
CREATE TABLE accessories (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
UNIQUE KEY (name) /* for efficient lookups by name */
);
CREATE TABLE car_accessories (
car INTEGER NOT NULL,
accessory INTEGER NOT NULL,
PRIMARY KEY (car, accessory),
UNIQUE KEY (accessory, car)
);
要列出除AC
,Turbo
,Cruise control
和CD
以外没有任何配件的所有车辆,您可以使用NOT EXISTS
子选择( SQLize):
SELECT *
FROM cars AS c
WHERE NOT EXISTS
( SELECT * FROM car_accessories AS ca, accessories AS a
WHERE ca.car = c.id
AND ca.accessory = a.id
AND a.name NOT IN ('AC', 'Turbo', 'Cruise control', 'CD') )
或LEFT JOIN
(SQLize):
SELECT c.*
FROM cars AS c
LEFT JOIN
( car_accessories AS ca
JOIN accessories AS a
ON ca.accessory = a.id
AND a.name NOT IN ('AC', 'Turbo', 'Cruise control', 'CD')
) ON ca.car = c.id
WHERE ca.car IS NULL
答案 1 :(得分:0)
更改架构,需要规范化
e.g。
Cars, ID, AccessoryID
Accessories, ID
然后
你的例子就像是
Accessories
1, AC
2, Turbo
3, Cruise Control...
和汽车会说
ID,Name
和CarAccessories
CarID, AccessoryID
对该批次进行排序后,您想要的是ALL查询..