简体   繁体   English

PHP MySQL选择一行不同的随机行

[英]PHP MySQL select random rows where a row is different

What Im Trying to achieve is selecting multiple rows randomly where a certain column is different from the last for example我试图实现的是随机选择多行,其中某一列与上一列不同,例如

SELECT * FROM mytable WHERE `column_for_duplicate_values` != '$thelastkey' ORDER BY RAND() LIMIT 10

the column for multiple values would hold for example:多个值的列将包含例如:

1 , 1 , 1 , 1 , 2, 5 , 6, 6 , 6 , 6 , 6 , 11 , 11 ,  11 , 19

and I want to select 1 from each.我想从每个中选择 1 个。 So I would get所以我会得到

1 , 2 , 5 , 6 , 11 , 19

The main problem with my solution may be that it's我的解决方案的主要问题可能是

  1. slow减缓
  2. not applicable不适用

    You need to have a primary unique id in your mytable您的mytable需要有一个主要的唯一 ID

     SELECT * FROM mytable WHERE id IN ( SELECT id FROM ( SELECT id, column_for_duplicate_values FROM mytable ORDER BY RAND()) AS rand GROUP BY column_for_duplicate_values ORDER BY RAND()) LIMIT 10;

The main concept is to first get a random list of all values with their id and the column you want to have unique values.主要概念是首先获取所有值的随机列表,其中包含它们的 id 和您想要具有唯一值的列。

From this result we group by the value we only want to have once and only return the id.根据这个结果,我们按我们只想拥有一次的值进行分组,并且只返回 id。 The main table will then select 10 random id's form this list.然后主表将从该列表中选择 10 个随机 ID。

I tried it with one of my db's.我用我的数据库之一试过了。 Should work with any table that has a unique id and some random other column.应该适用于任何具有唯一 ID 和一些随机其他列的表。

If you append ORDER BY id ASC will also sort the id's.如果您附加ORDER BY id ASC也会对 id 进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM