mysql - 从一列中随机选择 4 个数据,由 2 个不同的列区分

标签 mysql sql random

例如,我尝试从 MySQL 上的表中选择 4 个不同的随机数据,但我希望某些字段是唯一的;

我有一张 table

表名称“videos”,数据为;

id f2  f3  f4
-- --  --  --
1  a   q   C  
2  a   w   Y
3  b   e   C
4  b   r   Y
5  c   t   C
6  c   y   Y
7  d   u   C
8  d   o   Y

我想从 f3 中随机选择 4 个数据,但 f2 必须是唯一的。 f4 对于每个 f2 必须是唯一的,我的意思是我必须随机获得“u”或“o”,而不是两者。所以最后我想从唯一的f2中获取2xC数据列,并从唯一的f2中获取2xY数据。我想要得到的结果是这样的;

f3      f3        f3
--      --        --
q   or|  q   or|  w
r   or|  e   or|  r
t   or|  y   or|  t
o   or|  o   or|  u

这是我在 MsSql 中创建的示例,但无法将其转换为 MySQL;

select e.* from (
      select top 4 f2,
             ROW_NUMBER() OVER (ORDER BY newId()) AS RowNumber 
      from (
         select distinct(f2) from videos
      ) x
) a inner join (
      select top 4 ones.n,
             ROW_NUMBER() OVER (ORDER BY newId()) AS RowNumber 
      FROM (VALUES('C'),('Y'),('C'),('Y')) ones(n)
) b on a.RowNumber = b.RowNumber
inner join videos e on a.f2 = e.f2 and b.n =e.f4

最佳答案

如何对数据进行随机排序,然后使用 mysql ONLY_FULL_GROUP_BY 默认行为(禁用):

This causes MySQL to accept the preceding query. In this case, the server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate, which is probably not what you want. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause.

SQL Fiddle

MySQL 5.6 架构设置:

create table t ( id int, f2 char, f3 char, f4 char );
insert into t values
(1  ,'a'   ,'q'   ,'C'),
(2  ,'a'   ,'w'   ,'Y'),
(3  ,'b'   ,'e'   ,'C'),
(4  ,'b'   ,'r'   ,'Y'),
(5  ,'c'   ,'t'   ,'C'),
(6  ,'c'   ,'y'   ,'Y'),
(7  ,'d'   ,'u'   ,'C'),
(8  ,'d'   ,'o'   ,'Y');

查询 1:

select  f2, f3, f4
from (
 select f2, f3, f4
 from (
  select f2, f4, f3 from
   ( select f2, f4, f3
     from t
     order by rand()
   ) t0
  group by f2
 ) t1  
 order by RAND() 
) t2
group by f2, f4  

<强> Results :

| f2 | f3 | f4 |
|----|----|----|
|  a |  w |  Y |
|  b |  r |  Y |
|  c |  t |  C |
|  d |  o |  Y |

关于mysql - 从一列中随机选择 4 个数据,由 2 个不同的列区分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47976900/

相关文章:

mysql - 删除 mysql joomla 数据库中表中列中的千点

Mysql 唯一约束 > 16 列

mysql - 数据库选择

android - 在 Android 上的 SQL 数据库中存储日期和时间

scala - 随机连接两个数据框

mysql - 使用唯一的行 ID 更新 mysql 表行

PHP 搜索查询不工作

mysql - 使用 MySQL 将单元格值转换为列

php - 如何查找从随机表中选择的随机行

c - 如何在没有 rand() 函数的情况下生成随机数?