簡體   English   中英

在兩個表的左聯接中,選擇左表中的所有記錄,並從右表中僅選擇與左表匹配的一行記錄

[英]In Left Join of two table select all records from left table and select only one row record from right table that matches to left table

我有兩個表問答

我想選擇所有數學科目的問題,但只選擇其中一個問題。

$this->db->select('*');
    $this->db->from('questions');
    $this->db->join('answers','questions.id = answers.que_id', 'left'); //how to limit answers to 1
    $this->db->where('questions.subject', 'maths');
    return $this->db->get();

使用子查詢,

選擇問題,(從questions.id = answer.que_id的答案中選擇答案)作為questions.subject ='maths'的問題的答案;

請注意:這不是正在運行的SQL-只是了解一下

嘗試這樣的子查詢:

$this->db->select('*');
$this->db->from('answers');
$this->db->join('(select * from questions limit 1)','(questions.id = answers.que_id)', 'inner');
$this->db->where('questions.subject', 'maths');
return $this->db->get();

您的查詢應如下所示:

$query = 'select q.*, a1.* 
from questions AS q
    left join answers AS a1
        on a1.id = (select a2.id 
            from answers AS a2 
            where q.id = a2.que_id
            ORDER BY a2.id 
            limit 1
            );';
$query = $this->db->query($query);
$result = $query->result():

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM