MySQL 从列值中随机选择 2 个值?


若要随机选择,可使用 ORDER BY RAND()。若仅选择 2 个值,可在 MySQL 中使用 LIMIT 2。

mysql> create table DemoTable1815
     (
     Question text
     );
Query OK, 0 rows affected (0.00 sec)

首先,创建表 -

mysql> insert into DemoTable1815 values('What is your name?');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1815 values('What is your college name?');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1815 values('What is your nick name?');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1815 values('What is your enemy name?');
Query OK, 1 row affected (0.00 sec)

通过 INSERT 命令在表中插入一些记录 -

mysql> select * from DemoTable1815;

通过 SELECT 语句在表中显示所有记录 -

+----------------------------+
| Question                   |
+----------------------------+
| What is your name?         |
| What is your college name? |
| What is your nick name?    |
| What is your enemy name?   |
+----------------------------+
4 rows in set (0.00 sec)

这会产生以下结果 -

mysql> select * from DemoTable1815 order by rand() limit 2;

通过 SELECT 语句在表中显示所有记录 -

+----------------------------+
| Question                   |
+----------------------------+
| What is your college name? |
| What is your enemy name?   |
+----------------------------+
2 rows in set (0.00 sec)

AmitDiwan

更新于:2019-12-24

开始您的职业

通过完成课程获得认证

开始
广告