为时间最长的每个用户选择不同的信息

时间:2019-02-21 07:36:56

标签: php sql time 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

orders 表,其中存储了客户的订单详细信息。

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';

问题是它仅返回一条 SINGLE 记录,该记录最后输入的偶数名称与用户不同。在这种情况下,仅返回以下内容:

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

4 个答案:

答案 0 :(得分:1)

使用相关子查询

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)

答案 1 :(得分:0)

使用联接-

SELECT     t1.payable, 
           t1.time, 
           t1.NAME, 
           t1.floow, 
           t3.product 
FROM       reservation t1 
INNER JOIN 
           ( 
                    SELECT   Max(time) max_time, 
                             NAME 
                    FROM     reservation 
                    GROUP BY NAME) t2 t1.NAME=t2.NAME 
AND        t1.time=t2.max_time 
INNER JOIN product t3 
ON         ( 
                      t1.id=t3.id)

答案 2 :(得分:0)

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

答案 3 :(得分:0)

您可以尝试以下操作:

/* Create tables */

CREATE TEMP TABLE orders AS 
(
SELECT 1 AS id, 'A' AS product UNION
SELECT 2, 'B' UNION
SELECT 3, 'C' UNION
SELECT 4, 'D'
);

CREATE TEMP TABLE reservations AS 
(
SELECT 1 AS id, 24 AS payable, '02:40:10'::TIME AS time, 'Benjamin' AS name, '15th' AS floor UNION
SELECT 2, 36 , '02:29:10 '::TIME, 'Beverlyn', '15th'UNION
SELECT 3, 48 , '02:35:16'::TIME, 'Benjamin', '15th'UNION
SELECT 4, 30 , '02:32:51 '::TIME, 'Beverlyn', '15th'
);

/* Final Selection */

SELECT a.id
       , a.payable
       , a.time
       , a.name
       , a.floor
       , b.product
FROM reservations a
LEFT JOIN orders b on a.id = b.id
WHERE (name, time) IN (SELECT name, MAX(time) AS time
                       FROM reservations
                       GROUP BY 1)
ORDER BY 1;

或者,您也可以使用窗口功能。