mysql - SQL关联查询问题
巴扎黑
巴扎黑 2017-04-17 15:57:57
[MySQL讨论组]

我有两张表,
表一有字段
a_id,name

表二有字段
b_id,a_id,createtime

两个表的a_id是关联的,并且是一对多的关系。

请问怎么能通过1个sql
查询出 a_id,name,b_id

其中b_id是createtime最小的行对应的b_id.

巴扎黑
巴扎黑

全部回复(3)
ringa_lee

以下 SQL ok, 直接上图


附执行SQL

SELECT
    t1.a_id,
    t1. NAME,
    t2.b_id,
    t2.create_time
FROM
    a AS t1
LEFT OUTER JOIN b AS t2 ON t1.a_id = t2.a_id
WHERE
    t2.b_id = (
        SELECT
            b.b_id
        FROM
            b
        WHERE
            a_id = t1.a_id
        ORDER BY
            create_time ASC
        LIMIT 1
    )
ringa_lee
select tb1.a_id,tb2.b_id,name from tb1 
left join (select a_id,min(createtime) as min_time from tb2 group by a_id) t on t.a_id = tb1.a_id
left join tb2 on tb2.a_id = tb1.a_id and tb2.createtime = t.min_time

你看这样可行吗?

PHP中文网
create table a (a_id int,name varchar(15));
create table b (b_id int ,a_id int,create_time datetime);
insert into a set a_id=1,name='1';
insert into a set a_id=2,name='2';
insert into b set b_id=1,a_id=1,create_time=now();
insert into b set b_id=2,a_id=1,create_time=now();
insert into b set b_id=3,a_id=1,create_time=now();
insert into b set b_id=4,a_id=2,create_time=now();
insert into b set b_id=5,a_id=2,create_time=now();
select a.a_id,name,b_id,create_time from a,(select * from b group by a_id order by create_time asc ) c where a.a_id=c.a_id ;
+------+------+------+---------------------+
| a_id | name | b_id | create_time         |
+------+------+------+---------------------+
|    1 | 1    |    1 | 2016-11-24 18:34:56 |
|    2 | 2    |    4 | 2016-11-24 18:35:53 |
+------+------+------+---------------------+
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号