要在MySQL中获取随机行,请使用ORDER BY RAND()
。让我们首先创建一个表-
mysql> create table DemoTable1835
(
ListOfIds varchar(20)
);
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1835 values('10,20,30');
mysql> insert into DemoTable1835 values('70,80,90');
mysql> insert into DemoTable1835 values('45,67,89');
mysql> insert into DemoTable1835 values('98,96,49');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1835;
这将产生以下输出-
+-----------+
| ListOfIds |
+-----------+
| 10,20,30 |
| 70,80,90 |
| 45,67,89 |
| 98,96,49 |
+-----------+
4 rows in set (0.00 sec)
这是在MySQL中获取随机行的查询
mysql> select * from DemoTable1835
where ListOfIds NOT IN(10,20,70) order by rand() limit 2;
这将产生以下输出-
+-----------+
| ListOfIds |
+-----------+
| 98,96,49 |
| 45,67,89 |
+-----------+
2 rows in set, 4 warnings (0.00 sec)