【问题标题】:How can I query this in CodeIgniter如何在 CodeIgniter 中查询这个
【发布时间】:2013-04-25 16:30:39
【问题描述】:

这就是我想要的:

SELECT DISTINCT first_name,last_name 
FROM employees e 
INNER JOIN salaries s ON e.emp_no = s.emp_no 
WHERE e.birth_date > '1963-01-01' 
AND s.salary>150000

我已经尝试过了,我得到了我想要的名字,还有另外 12 个名字。出了点问题。

    $this->db->distinct();
    $this->db->select('first_name, last_name');
    $this->db->from('employees');
    $this->db->join('salaries s', 'e.emp_no = s.emp_no', 'inner');
    $this->db->where('e.birth_date > 1963-01-01');
    $this->db->where('s.salary > 150000');

    $result = $this->db->get();

【问题讨论】:

  • 你没有在 `$this->db->from('employees');` 中为 employees 加上别名,就像你为 salaries s 所做的那样在员工之后添加 e。跨度>

标签: mysql database codeigniter


【解决方案1】:

我添加了一条评论,但我会将其添加为建议的答案。您没有在 $this->db->from('employees'); 中使用别名 employees 在员工之后添加 e,就像您为薪水所做的那样。

$this->db->distinct();
$this->db->select('first_name, last_name');
$this->db->from('employees e');
$this->db->join('salaries s', 'e.emp_no = s.emp_no', 'inner');
$this->db->where('e.birth_date > 1963-01-01');
$this->db->where('s.salary > 150000');

$result = $this->db->get();

编辑: where 子句中的日期字符串没有被引用。尝试更新语句以引用字符串,或将其作为第二个参数传入。

$this->db->where('e.birth_date > "1963-01-01"');

$this->db->where('e.birth_date >', '1963-01-01');

我假设这是您数据库中日期列的正确格式掩码。

【讨论】:

  • 我最初在员工之后添加了 e,我正在尝试不同的东西,并在粘贴时忘记包含它。这给了我 15 个名字,而在 phpmyadmin 中运行 sql 查询只返回 3。
  • @ethio 我看到声明中没有引用日期字符串。您应该引用该字符串,或将其作为第二个参数传入。我已经更新了答案。
  • 是的,这就是我所做的并回答了这个问题,无论如何,谢谢。
  • @ethio 非常好。如果提供了正确答案,我们鼓励您标记。
  • 我在您编辑前 45 分钟留下了一个答案,我将把它标记为我的答案。
【解决方案2】:

如果活动记录让您感到困惑,这很容易。您可以简单地使用查询功能

$query  =   "SELECT 
                DISTINCT first_name,
                last_name 
            FROM employees e 
            INNER JOIN salaries s ON e.emp_no = s.emp_no 
            WHERE e.birth_date > '1963-01-01' 
            AND s.salary>150000";
$this->db->query($query);           

【讨论】:

    【解决方案3】:

    在 where 子句中,应在第一个参数中输入运算符,以便与第二个参数值进行比较。

    $this->db->where('e.birth_date >', 1963-01-01);
    $this->db->where('s.salary >', 150000'); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-23
      • 2015-08-05
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 2011-02-17
      相关资源
      最近更新 更多