Mysqli查询50%在参数内,另一半随机


mysqli query with 50% within parameter and other half random

我在这里纠结一个问题:

是否可以在我的sql中进行类似的查询:

  • 至少20%的结果来自A类
  • 至少15%的B类结果
  • 至少10%的结果来自C类
  • 至少10%的结果来自D类

,其余50%随机(a、b、c、d、e、f、g等类别)?

我已经试着搜索了一段时间,但没有找到一个好的答案,所以我希望这里的任何人都可以给一个好的提示。

提前感谢!!

在有人问我并给我一个拇指否定之前,我问这个是为了我可以分析我的网站访问者。这可不是随便问的。

PS: php标签是因为有时我用php函数来解决这类问题而这个网站是基于php的

我不知道你到底想做什么,但我认为你可以用不同的方法解决你的问题,但无论如何,我想到了你的问题,我脑海中唯一的想法是:

*假设你总共有5000行,你想只选择其中的50行,这50行根据你的百分比分布。

$limit = 50;
$cat_a_per = $limit *0.2; // 20% of the results
$cat_b_per = $limit *0.1; // 10% instead of yours 15% because 15% is incorrect ( try to sum percentages up :) ) 
$cat_c_per = $limit *0.1; // 10% of the results
$cat_d_per = $limit *0.1; // 10% of the results
$rest_per =  $limit*0.5; // the rest 50%
 // Now create a 5 mysql queries like the following :
"Select * From my_table where cat='A' limit $cat_a_per" ..
"Select * From my_table where cat='B' limit $cat_b_per" ..
"Select * From my_table where cat='C' limit $cat_c_per" ..
"Select * From my_table where cat='D' limit $cat_d_per" ..
 "Select * From my_table  limit $rest_per" ..

现在将结果汇总到一个数组中或使用UNION,您就可以开始了…