56,679
社区成员
发帖
与我相关
我的任务
分享
--建表语句
CREATE TABLE tt (
_id int(11) NOT NULL AUTO_INCREMENT,
_key int(11),
_orderCode int(11),
PRIMARY KEY (_id)
)
--插入数据
insert into tt(_key ,_orderCode ) values(1,0);
insert into tt(_key ,_orderCode ) values(2,1);
insert into tt(_key ,_orderCode ) values(3,2);
insert into tt(_key ,_orderCode ) values(4,3);
insert into tt(_key ,_orderCode ) values(5,1);
insert into tt(_key ,_orderCode ) values(1,2);
insert into tt(_key ,_orderCode ) values(2,0);
insert into tt(_key ,_orderCode ) values(3,1);
insert into tt(_key ,_orderCode ) values(6,1);
select * from tt t
where not exists (select 1 from tt where _key=t._key and _ordercode<t._ordercode)
mysql> SELECT * FROM tt;
+-----+------+------------+
| _id | _key | _orderCode |
+-----+------+------------+
| 1 | 1 | 0 |
| 2 | 2 | 1 |
| 3 | 2 | 0 |
| 4 | 3 | 2 |
| 5 | 4 | 3 |
| 6 | 5 | 1 |
| 7 | 1 | 2 |
| 8 | 2 | 0 |
| 9 | 3 | 1 |
| 10 | 6 | 1 |
+-----+------+------------+
10 rows in set (0.00 sec)
mysql> SELECT * FROM tt a WHERE NOT EXISTS(
-> SELECT 1 FROM tt WHERE a.`_key`=`_key` AND (a.`_orderCode`>`_orderCode`
-> OR a.`_orderCode`=`_orderCode` AND a._id>_id)
->
-> )
-> ;
+-----+------+------------+
| _id | _key | _orderCode |
+-----+------+------------+
| 1 | 1 | 0 |
| 3 | 2 | 0 |
| 5 | 4 | 3 |
| 6 | 5 | 1 |
| 9 | 3 | 1 |
| 10 | 6 | 1 |
+-----+------+------------+
6 rows in set (0.00 sec)
mysql>
mysql> SELECT * FROM tt;
+-----+------+------------+
| _id | _key | _orderCode |
+-----+------+------------+
| 1 | 1 | 0 |
| 2 | 2 | 1 |
| 3 | 2 | 1 |
| 4 | 3 | 2 |
| 5 | 4 | 3 |
| 6 | 5 | 1 |
| 7 | 1 | 2 |
| 8 | 2 | 0 |
| 9 | 3 | 1 |
| 10 | 6 | 1 |
+-----+------+------------+
10 rows in set (0.00 sec)
mysql> SELECT * FROM tt a WHERE NOT EXISTS(
-> SELECT 1 FROM tt WHERE a.`_key`=`_key` AND a.`_orderCode`>`_orderCode`
-> )
-> ;
+-----+------+------------+
| _id | _key | _orderCode |
+-----+------+------------+
| 1 | 1 | 0 |
| 5 | 4 | 3 |
| 6 | 5 | 1 |
| 8 | 2 | 0 |
| 9 | 3 | 1 |
| 10 | 6 | 1 |
+-----+------+------------+
6 rows in set (0.00 sec)
mysql>
select * from (select * from tt order by _orderCode) t group by _key
select * from tt t
where not exists (select 1 from tt where _key=t._key and (_ordercode<t._ordercode or _ordercode=t._ordercode and _id <t._id ))