编程语言
首页 > 编程语言> > php – ORDER BY RAND()用于多列(垂直每列的shuffle内容)

php – ORDER BY RAND()用于多列(垂直每列的shuffle内容)

作者:互联网

我正在寻找一个mysql解决方案,让几列从该列输出一个随机字段.

我现在的查询只是随机选择整行,但不随机化分隔的列.

$sql = "SELECT col1, col2, col3, col4 FROM table ORDER BY RAND() limit 4";

我试过子查询,但我不熟悉,所以如果有人可以帮助…

解决方法:

试试这个:

SELECT CASE rnd
          WHEN 1 THEN col1
          WHEN 2 THEN col2
          WHEN 3 THEN col3
          WHEN 4 THEN col4       
       END AS col          
FROM (       
  SELECT col1, col2, col3, col4,
         FLOOR(RAND() * 4) + 1 AS rnd
  FROM mytable 
ORDER BY RAND() ) AS t

表达式FLOOR(RAND()* 4)1生成1到4(含)之间的随机数.外部查询使用此数字随机选择表的4列中的一列.

Demo here

编辑:

如果要对列进行随机播放,可以使用以下查询:

SELECT CASE FIND_IN_SET(1, rnd)
          WHEN 1 THEN col1
          WHEN 2 THEN col2
          WHEN 3 THEN col3
          WHEN 4 THEN col4
       END AS c1,
       CASE FIND_IN_SET(2, rnd)
          WHEN 1 THEN col1
          WHEN 2 THEN col2
          WHEN 3 THEN col3
          WHEN 4 THEN col4
       END AS c2,
       CASE FIND_IN_SET(3, rnd)
          WHEN 1 THEN col1
          WHEN 2 THEN col2
          WHEN 3 THEN col3
          WHEN 4 THEN col4
       END AS c3,
       CASE FIND_IN_SET(4, rnd)
          WHEN 1 THEN col1
          WHEN 2 THEN col2
          WHEN 3 THEN col3
          WHEN 4 THEN col4
       END AS c4
FROM (  
  SELECT col1, col2, col3, col4, 
         (SELECT GROUP_CONCAT(i ORDER BY RAND()) 
          FROM (SELECT 1 AS i UNION ALL SELECT 2 UNION ALL 
                SELECT 3 UNION ALL SELECT 4) t) AS  rnd
  FROM mytable) AS t

Demo here

标签:php,mysql,random,subquery,multiple-columns
来源: https://codeday.me/bug/20190623/1269332.html