我无法用子查询来解决我的问题。如果您愿意,请继续:
样本数据:
CREATE TABLE users (
user_id INT(10) NOT NULL AUTO_INCREMENT,
username VARCHAR(64),
PRIMARY KEY (user_id)
);
CREATE TABLE cars {
car_id INT(10) NOT NULL AUTO_INCREMENT,
user_id INT(10),
caryear YEAR(4),
carmaker VARCHAR(32),
carmodel VARCHAR(32),
PRIMARY KEY (car_id, user_id)
FOREIGN KEY(`user_id`) references users(`user_id`)
) ENGINE=InnoDB;
INSERT INTO users (user_id, name) VALUES (1,'Bob'),(2,'John'),(3,'Sally');
INSERT INTO cars (user_id, caryear, carmaker, carmodel) VALUES
(1,'2004','Audi','A4'),
(1,'2006','Toyota','Camry'),
(1,'2014','Jeep','CJ'),
(2,'1998','Acura','CL'),
(2,'2014','Honda','Accord'),
(3,'2011','Jeep','Rubicon')
好的,所以如果我想获取用户及其汽车的列表,我可以这样做:
SELECT
user_id,
username,
(SELECT GROUP_CONCAT(CONCAT(CarYear,' ',CarMaker,' ',CarModel))
FROM cars
WHERE cars.user_id = users.user_id
) AS Cars
FROM users;
但是,例如,如何获取拥有 2004-2014 吉普车的用户列表?
我想出了这个,但我确信有一个更优雅的方法:
SELECT
user_id,
username,
(SELECT GROUP_CONCAT(CONCAT(CarYear,' ',CarMaker,' ',CarModel))
FROM cars
WHERE cars.user_id = users.user_id
AND CarMaker = 'Jeep'
AND CarYear BETWEEN 2004 AND 2014
) AS Cars
FROM users
HAVING Cars is not null;
此解决方案的问题在于,它不显示拥有 2004-2014 吉普车的人所拥有的其他汽车。
有什么建议吗?