Select mysql data with where clause in 2 tables

倾然丶 夕夏残阳落幕 提交于 2019-12-10 15:52:58

问题


I have 2 mysql tables like in the example below:

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

And I need to select all cars of 2 years old wich have ABS AND ESP. So it should return in this example: 3 Ford

If you have any idea...

Thanks


回答1:


The group by/having will ensure that the car has both of the desired features.

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



回答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



回答3:


You need to use a join on the OPTIONS table:

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

Or subqueries:

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')



回答4:


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

Will do ABS if you wanting more you will have to have PHP write the SQL additions per Options so your End result would be

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



回答5:


I suggest you change the 'age' column, either to 'date_created', or just leave it as age and only use an integer.

If you use as an integer, just do this:

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



回答6:


I also tried this way and returns me both of ford 1 and 3....

I only want 3 Ford the with abs and esp




回答7:


Try it::

  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`))

:)



来源:https://stackoverflow.com/questions/4805646/select-mysql-data-with-where-clause-in-2-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!