让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value char(1) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Value) values('X'); mysql> insert into DemoTable(Value) values('Y'); mysql> insert into DemoTable(Value) values('X'); mysql> insert into DemoTable(Value) values('X'); mysql> insert into DemoTable(Value) values('Y'); mysql> insert into DemoTable(Value) values('Z'); mysql> insert into DemoTable(Value) values('Z');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+-------+ | Id | Value | +----+-------+ | 1 | X | | 2 | Y | | 3 | X | | 4 | X | | 5 | Y | | 6 | Z | | 7 | Z | +----+-------+ 7 rows in set (0.00 sec)
情况1-以下是要分组但随机的查询-
mysql> select DemoTable.* from DemoTable join ( select Value, rand() as `random_Value` from DemoTable group by Value ) tbl2 on DemoTable.Value = tbl2.Value order by tbl2.`random_Value`;
这将产生以下输出-
+----+-------+ | Id | Value | +----+-------+ | 6 | Z | | 7 | Z | | 1 | X | | 3 | X | | 4 | X | | 2 | Y | | 5 | Y | +----+-------+ 7 rows in set (0.00 sec)
情况2-由于我们正在显示随机记录,因此让我们再次运行上述查询以显示-
mysql> select DemoTable.* from DemoTable join ( select Value, rand() as `random_Value` from DemoTable group by Value ) tbl2 on DemoTable.Value = tbl2.Value order by tbl2.`random_Value`;
这将产生以下输出-
+----+-------+ | Id | Value | +----+-------+ | 2 | Y | | 5 | Y | | 6 | Z | | 7 | Z | | 1 | X | | 3 | X | | 4 | X | +----+-------+ 7 rows in set (0.00 sec)