[英]MySQL return rows from last day only for a specific ID
I have 2 tables: 'clients' and 'orders', joined on the field 'client_id'. 我有2个表:“ clients”和“ orders”,并在字段“ client_id”上联接。
CREATE TABLE IF NOT EXISTS `clients` (
`client_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(120) NOT NULL,
PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
INSERT INTO `clients` (`client_id`, `name`) VALUES
(1, 'Ted Bundy'),
(2, 'Terry Towl');
CREATE TABLE IF NOT EXISTS `orders` (
`order_id` int(11) NOT NULL AUTO_INCREMENT,
`client_id` int(11) NOT NULL,
`description` varchar(70) NOT NULL,
`order_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`order_id`),
KEY `client_id` (`client_id`),
KEY `created` (`order_date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
INSERT INTO `orders` (`order_id`, `client_id`, `description`, `order_date`) VALUES
(1, 1, 'Shirt', '2015-12-02 01:14:01'),
(2, 2, 'Trousers', '2015-12-02 03:31:53'),
(3, 2, 'Underware', '2015-12-04 11:07:46'),
(4, 2, 'Hat', '2015-12-06 11:27:16'),
(5, 2, 'Scarf', '2015-12-07 00:14:31'),
(6, 2, 'Shirt', '2015-12-07 07:17:03'),
(7, 1, 'Shoes', '2015-12-09 16:23:20'),
(8, 1, 'Socks', '2015-12-11 11:40:16'),
(9, 1, 'Sweater', '2015-12-13 05:20:11'),
(10, 1, 'Shorts', '2015-12-13 12:41:31');
ALTER TABLE `orders`
ADD CONSTRAINT `orders_ibfk_1`
FOREIGN KEY (`client_id`)
REFERENCES `clients` (`client_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
I need to find the orders for the most recent day for a specific client_id, and only 1 client at a time 我需要查找特定client_id最近一次的订单,一次只能找到1个客户
Example output for client_id 2 client_id 2的示例输出
client_id | name | description | order_date
-------------------------------------------------------------
2 | Terry Towl | Hat | 2015-12-07
2 | Terry Towl | Scarf | 2015-12-07
The issue is that we dont know the number of orders on that day, nor the date 问题是我们不知道当天的订单数量,也不知道日期
The only way I can think to do this is to first query the date of the last order for a client, then to run another to find all records for that client on that date, however was hoping to be able to do this in one query. 我能想到的唯一方法是先查询一个客户的最后订单日期,然后运行另一个查询以查找该日期该客户的所有记录,但是希望能够在一个查询中做到这一点。 。
Does anyone have an idea how to achieve this in one query? 有谁知道如何在一个查询中实现这一目标?
Your idea is basically correct. 您的想法基本上是正确的。
select *
from clients c join
orders o
on c.client_id = o.client_id
where c.client_id = $client_id and
o.order_date = (select max(o2.order_date)
from orders o2
where o2.client_id = c.client_id
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.