关于mysql执行顺序为1和rand(1)?

时间:2016-12-22 08:12:03

标签: mysql random sql-order-by

在mysql中我构建了一个表,其id为int类型,名称和密码为varchar类型。 执行

select * from test.new_table order by rand(1);

然后结果是: enter image description here

这是因为在为rand设置种子后序列是固定的,我已经知道了。但是如果执行

select * from test.new_table order by 1 and rand(1);

然后结果是: enter image description here

对于这样的结果,我不明白。此外,如果按'xxx'执行订单,则会安排结果。 不太明白,希望你指点一下。

1 个答案:

答案 0 :(得分:0)

您可以在查询中查看表达式的结果:

mysql> select *, 1, rand(1), 1 and rand(1) from new_table order by 1 and rand(1);
+----+------+----------+---+---------------------+---------------+
| id | name | password | 1 | rand(1)             | 1 and rand(1) |
+----+------+----------+---+---------------------+---------------+
|  1 | ghi  | 111      | 1 | 0.40540353712197724 |             1 |
|  3 | abc  | 234      | 1 |  0.1418603212962489 |             1 |
|  5 | 5    | 5        | 1 | 0.04671454713373868 |             1 |
|  7 | 7    | 7        | 1 |     0.6108337804776 |             1 |
|  2 | jkl  | 123      | 1 |  0.8716141803857071 |             1 |
|  4 | def  | 555      | 1 | 0.09445909605776807 |             1 |
|  6 | 6    | 6        | 1 |  0.9501954782290342 |             1 |
+----+------+----------+---+---------------------+---------------+

了解布尔表达式如何始终生成1

正如@Barmar所描述的,任何表达式1 and n都会导致0或1,具体取决于n的值为零或非零。

所以你的表达式ORDER BY 1 AND RAND(1)就像ORDER BY true(一个常量表达式),这意味着排序是每一行之间的联系,而MySQL以任意方式对它们进行排序。

任意 random 不同。