1

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

我们有 4 个带有 - 列的表:

  1. table_cars - id | 品牌 | 类型 | 执照
  2. table_equipments - id | 姓名 | 描述
  3. table_distances - id_car | 日期 | 距离
  4. table_cars_equipments - id_car | id_设备

第一个查询应该显示所有具有“灭火器”设备并且昨天一直在行驶的汽车。

我试图写这个查询:

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

4

1 回答 1

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 = ?;

请注意:我使用了表的别名ce,而不是表的全名。

于 2013-10-01T12:00:19.207 回答