简体   繁体   English

如何以1到n的关系检索左表的一些随机行以及右表的所有相关行

[英]How to retrieve few random rows of left table and all the related rows from right table in 1 to n relationship

I have Two tables . 我有两张桌子。 One is Question with following properties: 一种是具有以下属性的问题:

  1. QuestionId QuestionId
  2. Question_Description 问题说明
  3. Weight 重量
  4. NoofOption NoofOption

and other is Answer with: 另一个是答案:

  1. Id ID
  2. QuestionId QuestionId
  3. IsCorrect 是正确的

Note: Question and Answer have 1 to n relation 注意: QuestionAnswer存在1到n的关系

Now I need to select 10 random questions from question table and get all the rows of answers using join. 现在,我需要从问题表中选择10个随机问题,并使用join获取所有答案行。 I am new to sub query. 我是子查询的新手。 :( :(

A subquery is definitely the way to go: 子查询绝对是必经之路:

SELECT
    q.questionID, 
    q.question_Description,
    q.weight,
    q.NoOfOption
FROM
    (SELECT QuestionID, Question_Description, Weight, NoOfOption FROM Question ORDER BY RAND() LIMIT 0,10) as q
    LEFT OUTER JOIN Answers a 
        ON q.questionid = a.questionid

The subquery here just grabs 10 random questions. 这里的子查询仅捕获10个随机问题。 Then we LEFT OUTER JOIN that over to Answers. 然后我们将OUTER JOIN移至Answers。

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

相关问题 从表中检索除laravel中的几行之外的所有行 - Retrieve all rows from table except few rows in laravel 如何从表 1 中检索在 MySQL 中表 2 中没有相关行的行 - How to retrieve rows from table 1 that have no related rows in table 2 in MySQL MySQL Join - 仅当所有右表行都满足 WHERE 子句时才检索左表行 - MySQL Join - Retrieve Left Table Rows only if all the Right Table Rows satisfies the WHERE clause 如何从SQL Server中的表中检索前N行或所有行 - How to Retrieve either Top N rows OR all rows from a table in SQL Server 如何从左表返回行,其中右表的条件在没有子查询的所有行上为真 - How to return rows from left table where condition on right table true on all row without sub query 返回LEFT表中的所有行,即使RIGHT表中没有记录,也返回RIGHT表中的最大到期日期 - Return all rows from LEFT table even no record in RIGHT table and maximum expiry date from RIGHT tables 如果有两个左连接,如何从左表中获取所有行 - How to get all rows from left table if there are two left join 如何从大表子集中选择mysql中的n个随机行? - how to select n random rows in mysql from subset of large table? MySql 查询从左表获取所有行,从右表获取公共行 - MySql query Get all rows from left table and common from right table SQL根据相关表值获取所有n:th行 - Sql get all n:th rows depending on related table value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM