doumi4974 2013-07-14 03:14
浏览 62
已采纳

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

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?

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!

This is how I select the answers currently... With 2 query's

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

// Just for testing the question_id is manually set

$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

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?

  • 写回答

2条回答 默认 最新

  • dongzan0108 2013-07-14 03:40
    关注

    may be use 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比