【问题标题】: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在两个表的左连接中,从左表中选择所有记录,并从右表中仅选择与左表匹配的一行记录
【发布时间】:2019-05-26 18:50:48
【问题描述】:

我有两张表 Questions and Answers

我想选择所有数学科目的问题,但只选择问题中的一个答案。

$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();

【问题讨论】:

  • 为什么不只是$this->db->limit(1)
  • 结果只有一个问题。
  • 我想从 Answers 表中获得所有主题的单一答案
  • 如果是我,我会先在原始 sql 中解决问题,然后弄清楚如何将其转录到您选择的框架中
  • 请在上面的代码中解释一下..谢谢。

标签: mysql codeigniter join limit


【解决方案1】:

使用子查询,

select question,(select answer from answers where questions.id = answers.que_id) as answer from questions where questions.subject='maths';

请注意:这不是一个正在运行的 SQL - 了解一下

【讨论】:

  • 尝试但不工作的情况 1:$this->db->join('answers','questions.id = (select que_id from answers where answers.que_id = questions.id limit 1)' , '左');
【解决方案2】:

试试这样的子查询:

$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();

【讨论】:

  • 不工作。显示与之前相同的结果。
  • 我已根据您的查询请求更新了答案
【解决方案3】:

您的查询应该是这样的:

$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():

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多