我怎样才能在 MySQL 中做到这一点?
SELECT TOP 50 PERCENT * FROM table
Run Code Online (Sandbox Code Playgroud)
在不运行单独查询的情况下(如果可能),最简单的方法是什么?
MySQL 中没有 TOP n PERCENT 语法。
你将不得不模仿它如下
首先这里是一个示例表
mysql> use test
Database changed
mysql> drop table if exists mytable;
Query OK, 0 rows affected (0.06 sec)
mysql> create table mytable (id int not null auto_increment primary key);
Query OK, 0 rows affected (0.06 sec)
mysql> insert into mytable values (),(),(),(),(),(),(),(),(),();
Query OK, 10 rows affected (0.07 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql> select * from mytable;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
+----+
10 rows in set (0.01 sec)
mysql>
Run Code Online (Sandbox Code Playgroud)
您可以使用以下代码模拟它:
set @percent = 50;
select floor(count(1) * @percent / 100.0) into @pct from mytable;
set @sqlstmt = concat('select * from mytable limit ',@pct);
prepare stmt from @sqlstmt;
execute stmt;
deallocate prepare stmt;
Run Code Online (Sandbox Code Playgroud)
这是执行的代码:
mysql> set @percent = 50;
Query OK, 0 rows affected (0.00 sec)
mysql> select floor(count(1) * @percent / 100.0) into @pct from mytable;
Query OK, 1 row affected (0.00 sec)
mysql> set @sqlstmt = concat('select * from mytable limit ',@pct);
Query OK, 0 rows affected (0.00 sec)
mysql> prepare stmt from @sqlstmt;
Query OK, 0 rows affected (0.01 sec)
Statement prepared
mysql> execute stmt;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
+----+
5 rows in set (0.00 sec)
mysql> deallocate prepare stmt;
Query OK, 0 rows affected (0.00 sec)
mysql>
Run Code Online (Sandbox Code Playgroud)
试一试 !!!
归档时间: |
|
查看次数: |
10306 次 |
最近记录: |