我有两个表格问题与答案
我想选择所有数学主题的问题,但只选择其中一个的答案。
$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();
答案 0 :(得分:0)
使用子查询,
选择问题,(从questions.id = answers.que_id的答案中选择答案)作为questions.subject =“数学”的问题的答案;
请注意:这不是正在运行的SQL-只是想出主意
答案 1 :(得分:0)
尝试这样的子查询:
$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();
答案 2 :(得分:0)
您的查询应如下所示:
$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():