鍍金池/ 問答/PHP  數(shù)據(jù)庫/ 如何查詢出最大的記錄

如何查詢出最大的記錄

現(xiàn)有用戶訂單表

用戶表user
id  name
1    小明
2    小紅



訂單表order
id  user  time
1     1    1516758140
2     1    1516757140
3     1    1516756140
4     2    1516759140
5     2    1516758140
6     2    1516757140


如何查出小紅跟小明時間戳最大的訂單(最新的訂單)在一個數(shù)組里 
回答
編輯回答
不討喜

1.用max函數(shù)查詢t_order表(我加了前綴,user表也是)并根據(jù)user分組,獲取最大的time數(shù)據(jù)
2.以步驟一的結(jié)果作為查詢條件,進行子查詢

字段名稱、表明有所調(diào)整,不要在意這些細節(jié)

select * from t_order o where EXISTS (select 1 from
(select max(t.time) tm,t.user_id uid from t_order t group by t.user_id) f
where o.time = f.tm and o.user_id = f.uid);
2017年3月23日 12:13
編輯回答
心癌
2017年7月13日 13:41
編輯回答
厭惡我

select * from order where time in(SELECT max(time) FROM order group by user);

2017年10月26日 09:30
編輯回答
病癮

select t1.*,t3.name from order t1
left join order t2 on t1.user=t2.user and t1.time<t2.time
left join user t3 on t1.user=t3.id
where t2.id is null

2017年10月13日 18:22
編輯回答
短嘆

你的最大是什么意思?最新的那條訂單?

2018年2月1日 09:36
編輯回答
毀了心

用max函數(shù)或者查詢的時候time倒序排列取一條,分別查出小明和小紅的數(shù)據(jù),然后再把他們放到一個數(shù)組中.

2018年4月13日 05:37
編輯回答
懷中人
select u.id,u.name,max(time) as mt from sg_order as o left join sg_user as u on o.user = u.id group by u.id
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 小明
            [2] => 1516759140
        )

    [1] => Array
        (
            [0] => 2
            [1] => 小紅
            [2] => 1516755140
        )

    [2] => Array
        (
            [0] => 3
            [1] => 小張
            [2] => 1516757140
        )

)

表數(shù)據(jù)
圖片描述

2017年6月12日 22:08