【问题标题】:I need help in phpmysql complicated queries我在 php mysql 复杂查询中需要帮助
【发布时间】:2021-03-04 10:25:27
【问题描述】:

我有三张桌子。表名是

  1. salary_history_table - employee_id(外键)
  2. employee_table - employee_id(primary) department_structure_id(foreign)
  3. department_table - department_structure_id(primary)

现在salary_history_table 有一个名为“employee_id”的id,它是employee_table 中的主键。并且employee_table 有一个名为“department_structured_id”的id,它是department_table 中的主键,我的问题是我想根据department_table 中的“department_structured_id”更新salary_history_table 列中名为rate_exempt 的所有数据。如何加入这三个表并根据employee_id 更新与特定id 查询相关的所有内容?

【问题讨论】:

  • 你试过什么?之前和之后的样本数据会是什么样子?编辑问题以包含这些详细信息。

标签: php mysql database codeigniter


【解决方案1】:

很简单,没那么复杂。只需使用下面的查询,让我告诉你它是如何工作的,首先,你必须调用一个具有两个值的表,在这里我在get() 中调用它,一旦你得到了两个 ID,那么你可以加入另一个表这些 ID。

$this->db->join('salary_history_table', 'salary_history_table.employee_id = employee_table.employee_id', 'left');
$this->db->join('department_table', 'department_table.department_structure_id = employee_table.department_structure_id', 'left');
$this->db->get('employee_table');

如果您还有任何问题,请告诉我。

【讨论】:

    【解决方案2】:

    首先,画出表格及其关系会很有帮助(为了在手机上打字,我已经缩短了名称)

    
    salary_history  employee          department
    employee_id —-> employee_id
    rate_exempt     department_id ——> department_id
    

    所以,如果你想列出所有部门所有员工的工资历史,

    select s.* 
    from department d 
    inner join employee e on e.department_id = d.department_id
    inner join salary_history s on s.employee.id = e.employee.id
    

    但是对于你的问题,如果你知道 department_id,你甚至不需要加入所有三个表

    select s.*
    from salary_history s
    inner join employee e on e.employee_id = s.employee_id
    where e.department_id = ?
    

    但如果您不知道部门 id,则必须根据部门名称进行匹配

    select s.*
    from salary_history s
    inner join employee e on e.employee_id = s.employee_id
    inner join department d on d.department_id = e.department_id
    where d.name = ?
    

    使用它,您可以设置更新。数据库系统之间的语法似乎有所不同,因此您必须查看哪种适合您

    update salary s
    inner join employee e on e.employee_id=s.employee_id
    inner join department d on d.department_id=e.department_id
    set rate_exempt = ?
    where d.name=?
    
    or,
    
    update ...
    set...
    inner join
    inner join
    where
    
    or,
    
    update salary
    set rate_exempt = ?
    where employee_id in (
        select e.employee_id
        from employee e
        inner join department d on d.department_id=e.department_id
        where d.name = ?
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多