Mysql 获取条目数的SQL查询

Mysql 获取条目数的SQL查询,mysql,sql,phpmyadmin,Mysql,Sql,Phpmyadmin,我试图根据指定的参数选择随机数目的条目 就像我有一张桌子 T( id, data1, data2 ,no); 现在no是一个包含随机数字串的字段 我想得到T的一个随机子集,使得no的数目是一个特定的值 例如,让我们假设我想要总no=7 T(0,a,a,4); T(1,B,B,4); T(2,v,v,1); T(3,d,d,2); T(4,d,d,3); 查询到查询的输出将是 T(0,a,a,4); T(4,d,d,3); 或 等等 这可能吗?我想不出一个逻辑。我能想到的最好办法就是一次检索

我试图根据指定的参数选择随机数目的条目

就像我有一张桌子

T( id, data1, data2 ,no);
现在no是一个包含随机数字串的字段

我想得到T的一个随机子集,使得no的数目是一个特定的值

例如,让我们假设我想要总no=7

T(0,a,a,4);
T(1,B,B,4);
T(2,v,v,1);
T(3,d,d,2);
T(4,d,d,3);
查询到查询的输出将是

T(0,a,a,4);
T(4,d,d,3);

等等

这可能吗?我想不出一个逻辑。我能想到的最好办法就是一次检索一行,然后继续计数“否”,但这样做效率很低


注意:如果计数超过0,这是可以接受的,但不是相反,这将使您非常接近

create table t ( name varchar(1), num tinyint ) ;

insert into t (name, num) values ( 'a', 4 ), ('b', 2), ('c', 3),
    ('d',1), ('e', 4), ('f', 1),('g', 6);
问题是:

select * from 
  (select name, num, @cum := @cum + num as cumulate from 
    (select * from t order by rand()) as t3, 
  (select @cum := 0 ) as t1 
  ) as t2
where cumulate <= 7;
这是一个例子。我相信它可以优化,但我很好奇如何创建它

select * from 
  (select name, num, @cum := @cum + num as cumulate from 
    (select * from t order by rand()) as t3, 
  (select @cum := 0 ) as t1 
  ) as t2
where cumulate <= 7;