mysql - SQL关联查询问题
问题描述
我有两张表,表一有字段 a_id,name
表二有字段 b_id,a_id,createtime
两个表的a_id是关联的,并且是一对多的关系。
请问怎么能通过1个sql查询出 a_id,name,b_id
其中b_id是createtime最小的行对应的b_id.
问题解答
回答1:以下 SQL ok, 直接上图
附执行SQL
SELECT t1.a_id, t1. NAME, t2.b_id, t2.create_timeFROM a AS t1LEFT OUTER JOIN b AS t2 ON t1.a_id = t2.a_idWHERE t2.b_id = (SELECT b.b_idFROM bWHERE a_id = t1.a_idORDER BY create_time ASCLIMIT 1 )回答2:
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_idleft join tb2 on tb2.a_id = tb1.a_id and tb2.createtime = t.min_time
你看这样可行吗?
回答3: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 |+------+------+------+---------------------+
相关文章:
1. objective-c - 如果Objective C 提供了一种新的语法,难道就没有地方去找到这种新语法的官方文档吗?而不是百度?2. javascript - 关于highchart数据渲染3. (横竖屏切换/强制横屏)CSS3 transform 怎样才能中心旋转?4. java代码如下,输出结果中为什么s对象?5. css3 - Y轴旋转导致字体和图片模糊6. javascript - 求助关于js正则问题7. html5 - 服务器的流量8. javascript - vue中如何使用mobiscroll插件9. 什么是前后端分离?用vue angular等js框架就能实现前后分离了吗?10. angular.js - angularjs的自定义过滤器如何给文字加颜色?
