急!高分求助!
假设一张表a分别有a1,a2,a3三个字段,a1是主键 ,a2是索引,a3是内容。a1,a2是类型是int,a3任意。现在想做到如下例子效果:
a1 a2 a3
1 1 A
2 2 B
3 2 C
4 2 D
5 3 E
6 3 F
7 4 G
设计一个数据库语句,使得如果limit 2的话,得到a1=7和a1=5的数据,如果limit 3的话,则得到a1=7,a1=5和a1=2的数据,因为该a表的记录总数有快200万行,所以希望各位能提供一个高效的解决该问题的数据库语句,先谢谢各位!
[解决办法]
select min(a1),a2,a3 from csdn group by a2 order by a1 desc limit 3;
[解决办法]
mysql> create table t1
-> (
-> a1 int not null auto_increment primary key,
-> a2 int not null,
-> a3 char(1) not null
-> );
Query OK, 0 rows affected (0.09 sec)
mysql> create index t_a2 on t1(a2);
Query OK, 0 rows affected (0.19 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> insert into t1 (a2,a3) values
-> (1, 'A '),
-> (2, 'B '),
-> (2, 'C '),
-> (2, 'D '),
-> (3, 'E '),
-> (3, 'F '),
-> (4, 'G ');
Query OK, 7 rows affected (0.16 sec)
Records: 7 Duplicates: 0 Warnings: 0
mysql> select * from t1 group by a2 order by a1 desc limit 2;
+----+----+----+
| a1 | a2 | a3 |
+----+----+----+
| 7 | 4 | G |
| 5 | 3 | E |
+----+----+----+
2 rows in set (0.00 sec)
mysql> select * from t1 group by a2 order by a1 desc limit 3;
+----+----+----+
| a1 | a2 | a3 |
+----+----+----+
| 7 | 4 | G |
| 5 | 3 | E |
| 2 | 2 | B |
+----+----+----+
3 rows in set (0.00 sec)