1

我无法用子查询来解决我的问题。如果您愿意,请继续:

样本数据:

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 吉普车的人所拥有的其他汽车。

有什么建议吗?

4

3 回答 3

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;
于 2013-11-01T22:10:56.680 回答
0

因为这是一个多对多的关系,你实际上需要cars分成两个表。第一个表将与cars现在相同,除了user_id从中删除。第二个表(称为它user_car)有两列:user_idcar_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
  ))
于 2013-11-01T21:23:29.867 回答
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 

内部联接

于 2013-11-01T21:23:50.787 回答