两个ORDER BY /随机选择一个

时间:2016-06-10 20:16:52

标签: php mysql

我有一个评论部分,按喜欢排序。

SELECT msg 
FROM msgs 
WHERE topic='$topic' 
ORDER BY likes_a ASC

SELECT msg 
FROM msgs 
WHERE topic='$topic' 
ORDER BY likes_b ASC

然而,由于我有2种喜欢,我希望每次刷新或加载页面时,随机地(或者喜欢_或者喜欢)对这些评论进行排序。但我不知道如何实现这一目标。

我会说:ORDER BY likes_a ASC OR ORDER BY likes_b ASC = AT RANDOM但显然这不是正确的编码。

4 个答案:

答案 0 :(得分:1)

最简单的方法是追加'通过SQL语句向表中添加新列并按其排序。最好的事情是GUID()。在MySQL中它应该是这样的:

SELECT msg FROM msgs WHERE topic='$topic' ORDER BY newid()
SELECT msg FROM msgs WHERE topic='$topic' ORDER BY newid()

答案 1 :(得分:1)

将随机变换为变量。

SELECT msg FROM msgs WHERE topic =' $ topic'订购' $ order' ASC

PHP

$options = ['likes_a', 'likes_b'];
$rand = array_rand($options, 1);
$order = $options($rand);

答案 2 :(得分:1)

由于您已经标记了PHP,我认为这符合该法案:

// Use PHP's rand() function to generate either a 0 or 1
// If rand() gives a 0 the use likes_a else use likes_b

$sql = "SELECT msg
          FROM msgs
         WHERE topic='$topic'
         ORDER BY likes_".(rand(0,1) === 0 ? 'a' : 'b')." ASC";

答案 3 :(得分:1)

您可以使用子查询随机选择一个值,使用它来选择一列。

SELECT msg, IF(@rnd < 0.5, likes_a, likes_b) AS sort
FROM msgs
WHERE topic = '$topic'
CROSS JOIN (SELECT @rnd := RAND()) AS r
ORDER BY sort ASC