如何联接四个表以显示特定数据

时间:2018-10-20 15:57:17

标签: php mysql database codeigniter

我在联接表时遇到了一些麻烦。我有四个桌子

“设备”表

equipment_id   equipment_name
-----------    --------------
1              Motor Cycle
2              Private Car

================================

这是我的项目表


project_id    project_name
----------    ------------
1              xyz trading 
2              abc private ltd

===============================

这是出租表


rental_id      project_id    equipment_id   Rental_date
---------------------------------------------------------
1                 2                 1         12/10/2018
2                 2                2          15/09/2018
3                 1                2          20/10/2018

这是删除表


remove_id      project_id    equipment_id   removal_date
---------------------------------------------------------
1                 2                 1         null
2                 2                2         14/10/18

these are my table, now i want to display data of single equipment (eg: equipment no 2) in which project this equipment ran, when was the rental date and when was the removal date from a project.

我想这样显示..(使用Codeigniter)

设备日志2

=======

    SN   Project Name      Rental date       Removal date
    ---  ------------      -----------       ------------
    1    ABC pvt Ltd        15/09/2018       14/10/2018
    2    xyz trading        20/10/2018         Null

控制器传递给模型

$data['eqipment_details']=$this->Equipment_model->getLog($equipment_id);

请帮助我进行查询

1 个答案:

答案 0 :(得分:1)

不得不猜测表名是什么,但是您应该可以对此进行调整:

SELECT
(@cnt := @cnt + 1) AS SN,
PROJECT.project_name AS Project Name,
RENTAL.Rental_date AS Rental date,
REMOVAL.removal_date AS Removal date 
FROM 
rental_table RENTAL 
LEFT JOIN project_table PROJECT ON (RENTAL.project_id = PROJECT.id) 
LEFT JOIN equipment_table EQUIPMENT ON (RENTAL.equipment_id = EQUIPMENT.id) 
LEFT JOIN removal_table REMOVAL ON (PROJECT.id = REMOVAL.project_id AND PROJECT.equipment_id = REMOVAL.equipment_id) 
WHERE 
EQUIPMENT.id = 2;

强烈建议您将驼峰大小写和标题大小写加下划线混合使用。