如何确保随机选择的两行彼此不同? [英] How can I make sure that two rows selected at random are different from one another?
问题描述
我有一个表 photos
里面有很多照片,我需要随机选择两张:
I have a table photos
with many photos in it and I need to select two at random:
在getnew.php
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$result2 = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row = $result->fetch_assoc();
$img1link = $row['link'];
// more stuff from $row
$row2 = $result2->fetch_assoc();
$img2link = $row2['link'];
// more stuff from $row2
但是我需要防止它两次选择同一张照片(所选照片必须不同),即$img1link
不应= $img2link
.然后我需要在另一个文件中使用 $.getJSON
检索数据,使用 getnew.php
末尾的数组.
However I need to prevent it from selecting the same photo twice (the selected photos must be different), i.e. $img1link
should not = $img2link
. I then need to retrieve the data using $.getJSON
in another file, using an array at the end of getnew.php
.
getnew.php 末尾的数组:
echo json_encode(array('img1'=>$img1link,'img2'=>$img2link, ...(etc)... ));
如何确保所选照片在变量存储在数组中时有所不同?我试图创建一个 if/else 语句,但并没有真正理解我在做什么.
How can I make sure the selected photos are different by the time the variable is stored in the array? I tried to create an if/else statement but didn't really understand what I was doing.
推荐答案
你可以只执行一次,但可以改为执行两次,这样你就永远不会选择同一行:
You can just execute once but get two instead so that you'll never pick the same row:
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");
$row = $result->fetch_assoc();
$row2 = $result->fetch_assoc();
// invoke `->fetch` twice to get the first and second row
$img1link = $row['link'];
$img2link = $row2['link'];
旁注:请注意 ORDER BY rand()
子句,因为它在大型数据集上会很慢.您可以使用@Bill Karwin 出色的answer
Sidenote: Be careful of that ORDER BY rand()
clause since it'll be slow on large data sets. You can use an alternative with @Bill Karwin's great answer
这篇关于如何确保随机选择的两行彼此不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!