我在使用子查询查询查询时遇到问题。如果您愿意,请继续:
示例数据:
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吉普车的人拥有的其他车辆。
有什么建议吗?
答案 0 :(得分:1)
为任何拥有Jeep 2004-2014的用户显示用户及其所有车辆列表:
SELECT
u.user_id,
u.username,
GROUP_CONCAT(CONCAT(c.CarYear,' ',c.CarMaker,' ',c.CarModel)) AS Cars
FROM users u
INNER JOIN cars c USING (user_id)
INNER JOIN (
SELECT DISTINCT user_id FROM cars
WHERE c.CarMaker = 'Jeep'
AND c.CarYear BETWEEN 2004 AND 2014) AS j USING (user_id)
GROUP BY u.user_id, u.username;
答案 1 :(得分:0)
因为这是一个多对多的关系,所以实际上你需要将cars
分成两个表。第一个表格与cars
现在相同,只是从中移除user_id
。第二个表格(称为user_car
)有两列:user_id
和car_id
。
一旦你这样做,查询很简单:
SELECT user_id FROM user_car WHERE car_id IN
(SELECT car_id FROM cars
WHERE CarMaker = 'Jeep'
AND CarYear BETWEEN 2004 AND 2014
)
如果您需要直接从users
提取数据,请将查询展开为:
SELECT user_id, username FROM users WHERE user_id IN
(SELECT user_id FROM user_car WHERE car_id IN
(SELECT car_id FROM cars
WHERE CarMaker = 'Jeep'
AND CarYear BETWEEN 2004 AND 2014
))
答案 2 :(得分:0)
INNER JOIN可以解决问题。
SELECT u.* FROM users u
INNER JOIN cars c ON c.user_id = u.user_id
WHERE CarMaker = 'Jeep' AND CarYear BETWEEN 2004 AND 2014