選擇某行和其他任意行的 MySQL 查詢?\n


若要選擇某行和另一任意行,可以使用 ORDER BY 和 RAND()。我們先建立一個示例表

mysql> create table oneSpecificRowAndOtherRandom
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.72 sec)

以下是使用插入命令在表中插入一些記錄的查詢

mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Larry');
Query OK, 1 row affected (0.56 sec)

mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Sam');
Query OK, 1 row affected (0.13 sec)

mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Mike');
Query OK, 1 row affected (0.12 sec)

mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Carol');
Query OK, 1 row affected (0.15 sec)

mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Chris');
Query OK, 1 row affected (0.21 sec)

mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Bob');
Query OK, 1 row affected (0.13 sec)

mysql> insert into oneSpecificRowAndOtherRandom(Name) values('David');
Query OK, 1 row affected (0.13 sec)

以下是使用選擇命令顯示錶記錄的查詢

mysql> select *from oneSpecificRowAndOtherRandom;

這將生成以下輸出

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Larry |
| 2  | Sam   |
| 3  | Mike  |
| 4  | Carol |
| 5  | Chris |
| 6  | Bob   |
| 7  | David |
+----+-------+
7 rows in set (0.00 sec)

以下是選擇某行和另一任意行的查詢

mysql> select *from oneSpecificRowAndOtherRandom ORDER BY (Id= 5) DESC, RAND() LIMIT 0,3;

這將生成以下輸出

+----+-------+
| Id | Name  |
+----+-------+
| 5  | Chris |
| 1  | Larry |
| 2  | Sam   |
+----+-------+
3 rows in set (0.05 sec)

讓我們再次執行相同的查詢以顯示任意記錄,因為已經使用了 RAND()

mysql> select *from oneSpecificRowAndOtherRandom ORDER BY (Id= 5) DESC, RAND() LIMIT 0,3;

這將生成以下輸出

+----+-------+
| Id | Name  |
+----+-------+
| 5  | Chris |
| 2  | Sam   |
| 4  | Carol |
+----+-------+
3 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

158 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始
廣告