MySQL select 1 row from inner join

六月ゝ 毕业季﹏ 提交于 2020-02-25 05:40:13

问题


I'm don't know the terms for this problem, the title might be a little bit misleading.

I'm trying to create a overview of a 1 to many table but only want to select 1 example of the relation table.

Car table

name
id

Car colours

car_id
color

A car can have many different colors. However I want to select just one color for the 'overview'. How can I do this? My tries result in a lot of results with multiple colors of the same car row.

Preferably in one query if possible.

Thanks in advance

edit:

I think my question is to vague. I'm trying to select all the cars within the car table but only 1 color (the first one it comes across).

Foo     blue
Bar     blue
Barfoo  yellow

etc

However Foo has the colors, blue,yellow,red,black etc.

As for table create query, this is a 'dummy' version. I'm just trying to learn how to solve this problem with a push into the right direction.


回答1:


You need a query like this:

SELECT * FROM car
INNER JOIN car_color ON car.id = car_color.car_id 
LIMIT 1 -- this will limit the results to only one row

edit: to get only one color for a car you can use group:

SELECT * FROM car
INNER JOIN car_color ON car.id = car_color.car_id 
GROUP BY car.id -- this will group all the rows with the same car to only one row per car



回答2:


How about this.

    CREATE table car(name varchar(10),id int primary key);
    CREATE table car_details(car_id int foreign key references car(id), color varchar(20));

    INSERT into car values('BMW',1);
    INSERT into car_details values(1,'Blue');

    INSERT into car values('toyota',2);
    INSERT into car_details values(2,'pink');

    SELECT * FROM
    car c INNER join car_details cd
    on c.id = cd.car_id
    limit 1;

    Results in.    

    name       id          car_id      color
---------- ----------- ----------- --------------------
    BMW        1           1           Blue



回答3:


SUBQUERY

select cc.color from CarColours cc,Car c where cc.car_id = c.id and c.id = 1 limit 1 


来源:https://stackoverflow.com/questions/10914079/mysql-select-1-row-from-inner-join

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