选择某行和其他任意行的 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)
广告