要选择一个特定行和另一个随机行,可以使用ORDER BY和RAND()
。让我们首先创建一个示例表:
mysql> create table oneSpecificRowAndOtherRandom -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20) -> );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Larry'); mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Sam'); mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Mike'); mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Carol'); mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Chris'); mysql> insert into oneSpecificRowAndOtherRandom(Name) values('Bob'); mysql> insert into oneSpecificRowAndOtherRandom(Name) values('David');
以下是使用select命令显示表中记录的查询:
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)