在MySQL中联接两个表,仅从第二个表返回一行 [英] Join two tables in MySQL, returning just one row from the second table

查看:137
本文介绍了在MySQL中联接两个表,仅从第二个表返回一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个桌子:图库和图片:

I have two tables: gallery and pictures:

图库

id           int (auto increment, primary key)
name         varchar

图片

id           int (auto increment, primary key)
picture      varchar
gallery_id   int (foreign key)

我如何连接这两个表,以显示左表(画廊)中的每一行,仅显示第二个表中的第一行,而不浏览第二个表中的所有行?我正在使用MySQL.

How do I join these two tables showing for each row from the left table (gallery) just the first row from the second table, without going through all the rows from the second table? I am using MySQL.

我的目标是制作一个包含现有画廊列表的页面,该列表显示每个画廊的图片,作为指向该画廊所有图片的详细信息页面的链接.

My objective is to make a page containing a list of the existing galleries showing a picture for each gallery as a link to the details page with all the pictures of that gallery.

我已经在此站点上搜索了这个问题,但是类似的问题太复杂了.我只对这个简单的例子感兴趣.

I have searched this question on this site but the similar questions are too complicated. I'm only interested in this simple example.

推荐答案

已编辑

显然,在MySQL数据库中分组将为您解决问题.

Apparently grouping in MySQL database would do the trick for you.

数据库列为main_id, sub_id, sub_main_id, sub_data

SELECT *
FROM tblmain
  inner join sub on sub.sub_main_id = main_id
group by main_id;

在没有群组的情况下,我有以下记录:

1, 1, 1, 'test 1'
1, 2, 1, 'test 2'
2, 3, 2, 'test 3'
3, 4, 3, 'test 4'
2, 5, 2, 'test 5'

分组后,我得到以下结果:

1, 1, 1, 'test 1'
2, 3, 2, 'test 3'
3, 4, 3, 'test 4'

这篇关于在MySQL中联接两个表,仅从第二个表返回一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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