一个为交易表,有唯一id,别名trade_id
一个为交易状态详情表,记录trade_id的多个状态。
进行了两个表查询。查询某个trade_id的交易情况及最新状态。
直接粘贴此sql,执行即知。
-- ----------------------------
-- Table structure for `trade_test`
-- ----------------------------
DROP TABLE IF EXISTS `trade_test`;
CREATE TABLE `trade_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '用户ID',
`create_at` int(11) NOT NULL COMMENT '创建时间',
`totalmoney` decimal(10,2) NOT NULL COMMENT '总金额',
`tid` int(11) NOT NULL COMMENT '交易编号',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='交易发起表';
-- ----------------------------
-- Records of trade_test
-- ----------------------------
INSERT INTO `trade_test` VALUES ('1', '1', '1451700000', '60.00', '1111');
INSERT INTO `trade_test` VALUES ('3', '2', '1451800000', '50.00', '2222');
DROP TABLE IF EXISTS `status_detail_test`;
CREATE TABLE `status_detail_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`trade_id` int(11) NOT NULL,
`status_name` varchar(10) DEFAULT NULL,
`brief` text COMMENT '状态说明',
`create_at` int(11) DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COMMENT='交易状态详情表';
-- ----------------------------
-- Records of status_detail
-- ----------------------------
INSERT INTO `status_detail_test` VALUES ('1', '1', 'START', null, '1453595414');
INSERT INTO `status_detail_test` VALUES ('2', '1', 'AGREE', null, '1453595753');
INSERT INTO `status_detail_test` VALUES ('3', '2', 'START', null, '1453898857');
INSERT INTO `status_detail_test` VALUES ('4', '2', 'AGREE', null, '1453941720');
INSERT INTO `status_detail_test` VALUES ('5', '2', 'PAY', null, '1453941924');
INSERT INTO `status_detail_test` VALUES ('6', '1', 'PAY', null, '1453942924');
INSERT INTO `status_detail_test` VALUES ('7', '1', 'TRANSFER', null, '1455564464');
INSERT INTO `status_detail_test` VALUES ('8', '1', 'COMPLETE', null, '1455670471');
SELECT
a.id as trade_id,
a.create_at as trade_create_at,
b.id as status_final_id,
b.status_name,
b.create_at as status_create_at
FROM
trade_test AS a ,
status_detail_test AS b
WHERE
b.trade_id = a.id
AND
b.create_at = (select max(create_at) from status_detail_test)
AND
a.id = 1
--
引用一简单的例子:
http://zhidao.baidu.com/link?url=15DnazEMsBVsoIs_M-WiFfLjt-YI8tEtuvL2yN7aEDe3x8cr4u_OgpgyUy1vJ4Pas3zzhZpQsY1fGs-KdFnI-q
例如:表字段id,name,age,
要求:取出所有年龄最大的一个纪录
按照年龄倒序排序,然后取第一条。
select id,name,age from 表 where age=(select max(age) from 表)