简体   繁体   English

MySQL在一个查询中选择具有唯一行的随机行

[英]MySQL selecting random rows with one unique row within one query

Is it possible to select x random rows from a table, where one of the rows have to be a special row (thereby with a special field value) within one query? 是否可以从一个表中选择x个随机行,其中一个查询中的某行必须是一个特殊行(因此具有特殊的字段值)?

Basically what I'm trying to create is a Guessing Game, where you have x amount of questions, with x amount of possible (checkbox selectable) answers! 基本上,我想创建的是一个猜谜游戏,其中您有x个问题,并且有x个可能的(可选的复选框)答案!

This is how I select the answers currently... With 2 query's 这就是我目前选择答案的方式...使用2个查询

$answers = 4; // This is the max amount of answers

// Just for testing the question_id is manually set //只是为了测试question_id是手动设置的

$query = "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` != 1 ORDER BY RAND() LIMIT " . ($answers - 1) . "";
$query = "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` = 1 LIMIT 1";

The "question_id" tells which question we are talking about, and the "correct" just tells if that field is the correct answer “ question_id”告诉我们我们在谈论哪个问题,而“正确”则告诉我们该字段是否是正确答案

So is it possible to select x random rows from a table, where one of the rows have to be "the correct one", within one query? 那么是否有可能从一个表中选择x个随机行,其中一个查询中的某一行必须是“正确的”?

may be use UNION ? 可能会使用UNION

$answers = 4;

$query = "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` != 1 ORDER BY RAND() LIMIT " . ($answers - 1) . "";

$query .= " UNION ";

$query .= "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` = 1 LIMIT 1";

With one single query, you will be able to get the desired result 通过一个查询,您将能够获得所需的结果

http://dev.mysql.com/doc/refman/5.0/en/union.html http://dev.mysql.com/doc/refman/5.0/en/union.html

$query = "SELECT * FROM answers WHERE ... whatever ... AND `question_id` IN (5, 9, 12, 16, 2)

So, you first find the number of rows and then put the correct answer's ID in to the WHERE IN statement. 因此,您首先要找到行数,然后将正确答案的ID放入WHERE IN语句中。 Because you know the one you want, you can just surround it with random IDs from the table and then render them in a random fashion. 因为您知道想要的那个,所以可以用表中的随机ID围绕它,然后以随机方式呈现它们。

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

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