从时间为MAX的每个用户中选择不同的信息

问题描述 投票:0回答:4

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 
php sql time max
4个回答
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)

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)

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

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;

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

© www.soinside.com 2019 - 2024. All rights reserved.