使用2个表中的where子句选择mysql数据

时间:2011-01-26 14:28:47

标签: sql mysql join one-to-many

我有2个mysql表,如下例所示:

CARS

Id     CAR NAME          AGE

1   Ford        2 years
2   AUDI        1 years 
3   Ford        2 years

OPTIONS

Id  id_car   option

1    1      ESP
2    2          ABS
3    3          ABS
4    3          ESP

我需要选择所有拥有ABS和ESP 的2岁车。 所以它应该在这个例子中返回:3福特

如果您有任何想法......

由于

7 个答案:

答案 0 :(得分:8)

小组by / have将确保汽车具有两种所需的功能。

select c.id, c.name
    from cars c
        inner join options o
            on c.id = o.id_car
                and o.option in ('ABS','ESP')
    where c.age = 2
    group by c.id, c.name
    having count(distinct o.option) = 2

答案 1 :(得分:2)

SELECT * FROM CARS WHERE id IN 
(SELECT id_car FROM OPTIONS WHERE GROUP_CONCAT(option) ='ABS,ESP' 
GROUP BY id_car) 
WHERE age ='2 years' GROUP BY CARS.name

答案 2 :(得分:0)

您需要在OPTIONS表上使用连接:

SELECT c.* FROM CARS c
JOIN OPTIONS o ON o.id_car=c.id AND o.option='ABS'
JOIN OPTIONS o2 ON o2.id_car=c.id AND o2.option='ESP'
WHERE c.age >= 2

或子查询:

SELECT c.* FROM CARS c
WHERE c.age >= 2
AND c.id IN ( SELECT o.id_car FROM OPTIONS o WHERE o.id_car=c.id AND o.option='ABS')
AND c.id IN ( SELECT o.id_car FROM OPTIONS o WHERE o.id_car=c.id AND o.option='ESP')

答案 3 :(得分:0)

SELECT * FROM CARS LEFT JOIN `OPTIONS` ON `OPTIONS`.`id_car` = `CARS`.`id` WHERE `OPTIONS`.`option` LIKE '%ABS%'

如果你想要更多,你会做必须让PHP为每个选项编写SQL添加,这样你的最终结果就是

SELECT * FROM CARS LEFT JOIN `OPTIONS` ON `OPTIONS`.`id_car` = `CARS`.`id` WHERE (`OPTIONS`.`option` LIKE '%ABS%' OR  `OPTIONS`.`option` LIKE '%ESP%')

答案 4 :(得分:0)

我建议您将'age'列更改为'date_created',或者将其保留为年龄并仅使用整数。

如果您使用整数,请执行以下操作:

SELECT c.id, c.car
   FROM cars c
   INNER JOIN options o
   ON o.id_car = c.id
   WHERE c.age >= 2

答案 5 :(得分:0)

我也尝试过这种方式并返回福特1和3 ......

我只想要3个福特与abs和esp

答案 6 :(得分:0)

试一下::

  Select new_car.name  
    From (select * from cars where year=2) as new_car 
    inner join option as op 
    on (op.id_car = new_car.id AND (op.option = `ABS` OR op.option = `ESP`))

:)