2014-06-26 66 views
0

我在這個結構SQL查詢來提取基於兩個條件

cars - id | brand | type | license 
equipments - id | name | description 
distances - id_car | date | distance 
cars_equipments - id_car | id_equipment 

四個表,我必須提取有裝備「滅火器」那個開車昨天所有的車......

我已成功地創建此到目前爲止

SELECT cars.id, cars.brand, cars.type, cars.license, cars_equipments.id_car 
FROM equipments 
INNER JOIN cars_equipments ON equipments.id = cars_equipments.id_equipment 
INNER JOIN cars ON cars.id = cars_equipments.id_car 
INNER JOIN distances ON distances.id_car = cars.id 
WHERE equipments.name LIKE 'fire extinguisher' 

這個只返回有「滅火器」,所以它不能正常工作一輛車,如果我添加

AND distances.date = DATE_SUB(NOW(), INTERVAL 1 DAY) 

將其與最後一天不起作用。

+0

不工作怎麼樣? –

+0

哪個DBMS是這個?如果查詢返回結果,爲什麼查詢無法正常工作? –

+0

在mySQL它只是返回空白當我添加date_sub() – user2842773

回答

0

它適合你嗎?

SELECT cars.id, cars.brand, cars.type, cars.license, cars_equipments.id_car 
FROM cars 
    INNER JOIN cars_equipments ON cars.id = cars_equipments.id_car 
    INNER JOIN equipments ON equipments.id = cars_equipments.id_equipment 
    INNER JOIN distances ON distances.id_car = cars.id 
WHERE equipments.name LIKE 'fire extinguisher' 
AND distances.date >= dateadd(day,datediff(day,0,GETDATE()),-1) 
AND distances.date < dateadd(day,datediff(day,0,GETDATE()),0) 

入住這sql fiddle