简体   繁体   English

随机且唯一的Mysql选择查询

[英]Random and unique Mysql select query

My Mysql database is filled with about 90 image links. Mysql数据库中充满了约90个图像链接。 However the ID of each row is not really chronological. 但是,每行的ID并非真正按时间顺序排列。 For example initially it goes from 6-20 then theres a gap where I deleted some. 例如,最初从6到20,然后有一个缺口,我删除了一些缺口。 Then it goes from 80 - 120 then another gap ect. 然后从80到120,再到另一个差距。

It is a hot or not website. 这是一个热门或不热门的网站。 I want the user to be able to go through all 90 images without having to view the same one twice. 我希望用户能够浏览所有90张图像,而不必两次查看同一张图像。 However at the moment every so often this happens. 但是,此刻每时每刻都在发生。 The same image comes up twice or even three times. 同一张图片出现两次或什至三次。

Here is my select query right now: 这是我现在的选择查询:

$sql = mysql_query("SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `content`)  ORDER BY rand() LIMIT 1");

Does anyone know any better solutions to this problem? 有谁知道这个问题更好的解决方案?

You could store the id's of the 'things' that the user has seen, and exclude them in all the next pages (either by a join or a not in). 您可以存储用户已看到的“事物”的ID,并将其排除在所有接下来的页面中(通过联接或不在其中)。 In that way you can always get a random post and not be stuck with the order that the rows have in the database (and what if the user returns later on?). 这样,您总是可以得到一个随机的帖子,而不会陷入数据库中行的顺序的困扰(如果用户稍后返回该怎么办?)。

如何从数据库中获取所有索引,对其进行混排,创建列表,然后将它们从一页传递到另一页,显示最上面的索引并将其从列表中删除,该怎么办?

The problem that you are facing is one with rand() itself. 您面临的问题是rand()本身存在的问题。 Each time you call it, it produces a different order. 每次您调用它时,它都会产生不同的顺序。 Random is random, so a given row could occur twice in a row. 随机是随机的,因此给定的行可能连续出现两次。 What you are really looking for is a random permutation. 您真正要寻找的是随机排列。

One approach is random with a seed followed by limit with offset: 一种方法是随机植入种子,然后加上偏移量limit

select *
from table t
order by rand(<seed value here>)
limit <offset>, 1;

The two things you need are a seed value. 您需要的两件事是种子值。 You can do this by just keeping an enumerated value for each user, or using the user id, or something that is an integer and a constant for each user. 您可以通过仅保留每个用户的枚举值或使用用户ID或每个用户的整数和常数的方式来执行此操作。

The other thing you need is the offset. 您需要的另一件事是偏移量。 This is important, because when you get the second item, you need to be sure that the ordering is the same as for the first item. 这很重要,因为获得第二个项目时,需要确保订购顺序与第一个项目相同。

Another approach is to fetch all the ids in random order the first time and to stash them in the application. 另一种方法是第一次以随机顺序获取所有id,并将其存储在应用程序中。 You can do this using group_concat() : 您可以使用group_concat()做到这一点:

select group_concat(id order by rand())
from table t;

Then go through this list instead of returning to the database. 然后遍历此列表,而不是返回数据库。

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

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