[英]Left Join - Select ALL from left table but select only the latest from right table
[英]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.