国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

mysql - SQL關(guān)聯(lián)查詢問題

瀏覽:123日期:2022-06-17 08:58:37

問題描述

我有兩張表,表一有字段 a_id,name

表二有字段 b_id,a_id,createtime

兩個(gè)表的a_id是關(guān)聯(lián)的,并且是一對(duì)多的關(guān)系。

請(qǐng)問怎么能通過1個(gè)sql查詢出 a_id,name,b_id

其中b_id是createtime最小的行對(duì)應(yīng)的b_id.

問題解答

回答1:

以下 SQL ok, 直接上圖mysql - SQL關(guān)聯(lián)查詢問題mysql - SQL關(guān)聯(lián)查詢問題mysql - SQL關(guān)聯(lián)查詢問題

附執(zhí)行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 |+------+------+------+---------------------+

相關(guān)文章:
主站蜘蛛池模板: 驻马店市| 甘肃省| 景德镇市| 永德县| 历史| 饶平县| 葵青区| 休宁县| 北辰区| 巴彦淖尔市| 云浮市| 措勤县| 秦皇岛市| 灵山县| 罗甸县| 大邑县| 迁西县| 搜索| 阜康市| 临湘市| 南靖县| 措勤县| 黑龙江省| 巴南区| 綦江县| 绥宁县| 图片| 新津县| 清涧县| 呼玛县| 内江市| 新竹市| 忻城县| 怀仁县| 临城县| 晋城| 南川市| 江门市| 锡林郭勒盟| 新泰市| 平阳县|