首页 > 代码库 > 查询出所有首笔订单金额超过1000的会员卡号及其首笔订单金额

查询出所有首笔订单金额超过1000的会员卡号及其首笔订单金额

题目源自:http://www.cnblogs.com/xpivot/p/4143069.html#!comments

有一张ER图描述数据结构,简单文字描述如下,劳烦看官各种脑补主外键关系:

一张会员表(account),字段有会员id(account_id), 会员卡号(account_num)。。。

一张交易订单表(trans),字段有会员id(account_id),交易时间(trans_time),交易金额(sales)。。。

要求查询出所有首笔订单金额超过1000的会员卡号及其首笔订单金额,

注:

1. 首笔订单指的是每个会员交易时间最小的一笔订单

2. 会员表有一千万笔记录

3. 如果会员没有任何订单或者首笔订单金额不足1000,则首笔订单金额返回0。

根据题目描述,建表

account表如下:

语句如下:

/*Navicat MySQL Data TransferSource Server         : localhostSource Server Version : 50614Source Host           : localhost:3306Source Database       : amydbTarget Server Type    : MYSQLTarget Server Version : 50614File Encoding         : 65001Date: 2014-12-04 19:23:39*/SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for `account`-- ----------------------------DROP TABLE IF EXISTS `account`;CREATE TABLE `account` (  `keyID` int(4) NOT NULL AUTO_INCREMENT,  `account_id` varchar(50) NOT NULL,  `account_card` varchar(50) NOT NULL,  PRIMARY KEY (`keyID`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;-- ------------------------------ Records of account-- ----------------------------INSERT INTO `account` VALUES (1, tianxue, 1251859009@qq.com);INSERT INTO `account` VALUES (2, xiaohua, 2804163771@qq.com);
View Code

trans表如下:

语句如下:

/*Navicat MySQL Data TransferSource Server         : localhostSource Server Version : 50614Source Host           : localhost:3306Source Database       : amydbTarget Server Type    : MYSQLTarget Server Version : 50614File Encoding         : 65001Date: 2014-12-04 19:23:46*/SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for `trans`-- ----------------------------DROP TABLE IF EXISTS `trans`;CREATE TABLE `trans` (  `keyID` int(4) NOT NULL AUTO_INCREMENT,  `account_id` varchar(50) NOT NULL,  `trans_time` datetime NOT NULL,  `sales` int(8) NOT NULL,  PRIMARY KEY (`keyID`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;-- ------------------------------ Records of trans-- ----------------------------INSERT INTO `trans` VALUES (1, tianxue, 2014-12-22 18:38:20, 100);INSERT INTO `trans` VALUES (2, xiaohua, 2014-12-08 18:38:38, 200);INSERT INTO `trans` VALUES (3, tianxue, 2014-11-12 18:38:51, 2000);INSERT INTO `trans` VALUES (4, xiaohua, 2014-12-31 18:39:07, 2000);
View Code

根据题目条件只有结果应该为:

下面是我的查询语句,结果是对的,只是没有考虑效率。

SELECT account.account_id, account.account_card, coalesce(c.sales,0) salesFROM account LEFT JOIN        (        SELECT a.account_id, a.sales        FROM  trans AS a INNER JOIN            (SELECT account_id, min(trans_time) AS firstTime            FROM trans            GROUP BY account_id) AS b            ON a.account_id=b.account_id              WHERE a.sales > 1000 AND a.trans_time = b.firstTime) AS con account.account_id = c.account_id
coalesce这个是什么?刚从网上找的。

有没有更高效的呢?

 

查询出所有首笔订单金额超过1000的会员卡号及其首笔订单金额