存在以下表格:
+----------------------+
| Tables_in_automobile |
+----------------------+
| car has options |
| car sold |
| company |
| customer |
| members |
| model |
| model has options |
| options |
+----------------------+
MariaDB [automobile]> describe model;
+-----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+-------+
| company name | varchar(100) | NO | PRI | NULL | |
| model name | varchar(100) | NO | PRI | NULL | |
| number of seats | int(10) | NO | | NULL | |
| cost | int(10) | NO | | NULL | |
+-----------------+--------------+------+-----+---------+-------+
MariaDB [automobile]> describe options;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| option name | varchar(100) | NO | | NULL | |
| cost | int(10) | NO | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
MariaDB [automobile]> describe `model has options`;
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| company name | varchar(100) | NO | MUL | NULL | |
| model name | varchar(100) | NO | | NULL | |
| option id | int(10) | YES | MUL | NULL | |
+--------------+--------------+------+-----+---------+-------+
我需要找到满足以下要求的特定车型:
以下查询满足第一个条件,但是如果任何汽车有任何一个或多个 通过查询提供的选项 ,它包含在结果中。我只需要那些提供了确切选项的汽车:
SELECT `company name`, `model name`, `number of seats`,
SUM(`options`.`cost`)+`model`.`cost` AS 'cost'
FROM `model` NATURAL JOIN `model has options` JOIN `options`
WHERE `model has options`.`option id` = `options`.`id`
AND `number of seats`>=3
AND `option id` IN (3,4,7)
GROUP BY `company name`, `model name`
ORDER BY `cost`
答案 0 :(得分:1)
HAVING子句可用于确保不同匹配选项的数量等于所提供选项的数量。
SELECT `company name`, `model name`, `number of seats`,
SUM(`options`.`cost`)+`model`.`cost` AS 'cost'
FROM `model` NATURAL JOIN `model has options` JOIN `options`
WHERE `model has options`.`option id` = `options`.`id`
AND `number of seats`>=3
AND `option id` IN (3,4,7)
GROUP BY `company name`, `model name`
HAVING COUNT(DISTINCT (`option id`)) = 3
ORDER BY `cost`
答案 1 :(得分:0)
另一种方法
SELECT Field FROM model
WHERE FIND_IN_SET(Field, "company name,model name,number of seats") = 0;
这样的东西会找到不在该数组中的任何Field
值。返回空集表示已找到所有。另一种方法是SELECT COUNT(*) FROM ...
限制:由于逗号用作分隔符,因此数组中的任何项都不能使用逗号。