如何在 MySQL 中使用逗號分隔值獲取隨機行?


要獲取 MySQL 中的隨機行,請使用 ORDER BY RAND()。我們首先建立一個表 -

mysql> create table DemoTable1835
     (
     ListOfIds varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

使用插入命令在表中插入一些記錄 -

mysql> insert into DemoTable1835 values('10,20,30');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1835 values('70,80,90');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1835 values('45,67,89');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1835 values('98,96,49');
Query OK, 1 row affected (0.00 sec)

使用 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)

更新於:2019-12-24

175 閱讀量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.