首页 > 解决方案 > 从时间为 MAX 的每个用户中选择不同的信息

问题描述

A 有一个看起来像这样的预订:

id    payable      time       name     floor
 1      24       02:40:10   Benjamin   15th      
 2      36       02:29:10   Beverlyn   15th
 3      48       02:35:16   Benjamin   15th
 4      30       02:32:51   Beverlyn   15th

还有一个订单表,其中存储了客户的订单详细信息。

id     product                
 1        A                   
 2        B               
 3        C                
 4        D               

我只想返回插入的每个用户的最新记录。像这样的东西:

  payable      time       name    floor    product
    24       02:40:10   Benjamin   15th      A  
    30       02:32:51   Beverlyn   15th      D

尝试查询:

SELECT reservation.payable, reservation.time, reservation.name, reservation.floor, orders.product
FROM orders
INNER JOIN reservation
ON orders.id = reservation.id 
WHERE reservation.time =
(SELECT MAX(time)
FROM reservation)
&& reservation.floor='15th';

问题是它只返回一个最后输入的单条记录,甚至用户名是不同的在这种情况下只返回这个:

 payable      time       name    floor    product
    24       02:40:10   Benjamin   15th      A 

标签: phpsqltimemax

解决方案


使用相关子查询

SELECT r.*,o.product
FROM reservation r
join order o ON o.id = r.id 
where r.time =( select max(time) from reservation r1 where r1.name=r.name)

推荐阅读