在购买记录表中查询每个用户在最新一条购买记录

数据库:mysql

表结构及测试数据sql:

/*
Navicat MySQL Data Transfer

Source Server         : 127.0.0.1
Source Server Version : 50617
Source Host           : localhost:3306
Source Database       : test

Target Server Type    : MYSQL
Target Server Version : 50617
File Encoding         : 65001

Date: 2019-04-26 15:39:37
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for shop_record
-- ----------------------------
DROP TABLE IF EXISTS `shop_record`;
CREATE TABLE `shop_record` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `shop_id` int(11) DEFAULT NULL,
  `tm` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of shop_record
-- ----------------------------
INSERT INTO `shop_record` VALUES ('1', '1', '2', '2019-04-23 16:56:35');
INSERT INTO `shop_record` VALUES ('2', '1', '1', '2019-04-24 16:56:58');
INSERT INTO `shop_record` VALUES ('3', '2', '2', '2019-04-22 16:57:18');
INSERT INTO `shop_record` VALUES ('4', '2', '1', '2019-04-21 16:57:34');
INSERT INTO `shop_record` VALUES ('5', '3', '2', '2019-04-20 16:57:56');
INSERT INTO `shop_record` VALUES ('6', '3', '1', '2019-04-22 16:58:10');

截图:

在购买记录表中查询每个用户在最新一条购买记录

SQL:

方法一:

SELECT
	r.user_id,
	r.shop_id,
	r.tm
FROM 
(
		SELECT
			user_id,
			MAX(tm) AS tm
		FROM
			shop_record
		GROUP BY
			user_id
	) tmp,
	shop_record r
WHERE
	tmp.user_id = r.user_id
AND tmp.tm = r.tm;

方法二:

SELECT
	r.user_id,
	r.shop_id,
	r.tm
FROM
	(
		SELECT
			user_id,
			shop_id,
			tm
		FROM
			shop_record
	) tmp,
	shop_record r
WHERE
	r.user_id = tmp.user_id
AND r.tm > tmp.tm

其实以上两种方法差不多,都用到了子查询。

上一篇:yii2验证规则


下一篇:(九)硅谷外卖前端部分-各导航路由组件(静态)