SQL连接有4个表

时间:2013-10-01 11:56:31

标签: sql join

我在这里有一个问题,我对外部/内部连接和多个条件有点困惑

我们有4个表 - 列:

  1. table_cars - id |品牌|类型|许可证
  2. table_equipments - id |名字|描述
  3. table_distances - id_car |日期|距离
  4. table_cars_equipments - id_car | id_equipment
  5. 首先查询应显示所有装有“灭火器”并且昨天开车的车辆。

    我试过写这个查询:

    SELECT  table_cars_equipments.id_car
    FROM    table_equipments
    INNER JOIN table_cars_equipments 
        ON table_equipments.id = table_cars_equipments.id_equipment
        AND table_equipments.name LIKE 'fire extinguisher';
    

    虽然我仍然很困惑如何添加昨天开车的车,但我不知道如何与表table_distances建立联系。

1 个答案:

答案 0 :(得分:1)

将另一个JOIN添加到表table_cars,将另一个table_distances添加到表WHERE。然后在SELECT c.id, c.brand, c.type, c.license ce.id_car, ... from table_equipments AS e INNER JOIN table_cars_equipments AS ce ON e.id = ec.id_equipment INNER JOIN table_cars AS c ON c.id = ce.id_car INNER JOIN table_distances AS d ON d.id_car = c.id WHERE e.name LIKE 'fire extinguisher' AND d.date = ?; 子句中添加一个条件,以便仅获取昨天开车的那些车辆。像这样:

c

请注意:我使用了表e,{{1}}等的别名,而不是表格的全名。