MySQL从内部联接中选择1行 [英] MySQL select 1 row from inner join

查看:102
本文介绍了MySQL从内部联接中选择1行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道此问题的用语,标题可能有点误导人.

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

我正在尝试创建1对多表的概述,但只想选择1个关系表示例.

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

汽车桌子

name
id

汽车颜色

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.

最好在一个查询中.

预先感谢

我认为我的问题是模糊的.我正在尝试选择车表中的所有汽车,但只能选择一种颜色(它遇到的第一种颜色).

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

但是Foo具有蓝色,黄色,红色,黑色等颜色.

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.

推荐答案

您需要这样的查询:

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

这篇关于MySQL从内部联接中选择1行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆