gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 18:04:46 25 4
gpt4 key购买 nike

例如,我尝试从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com