MySQL仅针对特定ID

时间:2015-12-13 01:36:22

标签: mysql

我有两个表:'客户'和'订单',加入了'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;

我需要找到特定client_id的最近一天的订单,一次只找到一个客户

client_id 2的示例输出

 client_id  |     name     |   description   |   order_date
-------------------------------------------------------------
      2     |  Terry Towl  |        Hat      |   2015-12-07
      2     |  Terry Towl  |       Scarf     |   2015-12-07

问题是我们不知道当天的订单数量,也不知道日期

我能想到的唯一方法是首先查询客户端的最后一个订单的日期,然后运行另一个订单以查找该客户端在该日期的所有记录,但希望能够做到这一点在一个查询中。

有人知道如何在一个查询中实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

你的想法基本上是正确的。

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