来自多个表的Mysql结果,其中不显示id匹配

时间:2014-01-14 12:43:29

标签: mysql sql

您好我有一个包含5个表的数据库: 用户, 驱动器, 客户端, 驱动程序, 车辆。

我正在尝试使用相应的车辆驱动程序和客户端获取所有驱动器。 我提出了以下问题:

SELECT drives.id,
drives.driver AS driver_id,
CONCAT(LEFT(drivers.name, 1), '. ', drivers.surname) AS driver_name,
drives.client AS client_id,
CONCAT(LEFT(clients.name, 1), '. ', clients.surname) AS client_name,
drives.vehicle AS vehicle_id,
vehicles.license_plates AS license_plates,
drives.departure,
drives.destination,
drives.distance,
drives.type,
drives.payment_type,
drives.timestamp,
drives.total,
drives.expenses,
drives.profit,
CASE
    WHEN DATE(drives.timestamp) < DATE(NOW()) AND drives.total > 0 THEN 'Completed'
    WHEN DATE(drives.timestamp) < DATE(NOW()) AND drives.total = 0 THEN 'Overdue'
    WHEN DATE(drives.timestamp) >= DATE(NOW()) THEN
        CASE
            WHEN drives.total = 0 THEN 'Pending'
            WHEN drives.total > 0 THEN 'Prepaid'
        END     
END AS payment_status,
DATE_FORMAT(drives.timestamp, '%d-%m-%Y %H:%i:%s') AS 'stamp'
FROM drives, clients, drivers, vehicles WHERE 
drives.driver = drivers.id AND
drives.client = clients.id AND
drives.vehicle = vehicles.id AND
drives.user = '146' ORDER BY id ASC LIMIT 9999999999 OFFSET 0

一切正常,但是如果我从车辆表中删除车辆记录然后尝试从表驱动器中获取所有驱动器记录,则驱动器记录中有drive.vehicle = vehicle.id(不再存在)将不会打印出来。

你可以理解这不是我想要的。即使车辆,客户端,驱动程序被删除,我也希望打印出所有的驱动器记录。

驱动器表的数据示例:

id  timestamp               user    driver  client  vehicle departure   destination distance    type        payment_type    total   expenses    profit  note
1   2013-02-14 10:33:26     146     1       1       1       Address 1   Address 2   0           Deprature   Cash            0       0           0       hello world

2 个答案:

答案 0 :(得分:2)

您当前正在使用INNER JOIN,请考虑使用OUTER JOIN

...
FROM drives 
LEFT OUTER JOIN clients ON drives.client = clients.id
LEFT OUTER JOIN drivers  ON drives.driver = drivers.id
LEFT OUTER JOIN vehicles ON drives.vehicle = vehicles.id
WHERE
.... 

答案 1 :(得分:0)

你应该在这里使用JOINS,这肯定有助于捕获NULL值,LEFT JOIN应该有帮助

SELECT DRI.id, DRI.driver AS driver_id, CONCAT(LEFT(DI.name, 1), '. ', DI.surname) AS driver_name,
DRI.client AS client_id, CONCAT(LEFT(CI.name, 1), '. ', CI.surname) AS client_name,
DRI.vehicle AS vehicle_id, vehicles.license_plates AS license_plates, DRI.departure,
DRI.destination, DRI.distance, DRI.type, DRI.payment_type, DRI.timestamp, DRI.total,
DRI.expenses, DRI.profit,
CASE
    WHEN DATE(DRI.timestamp) < DATE(NOW()) AND DRI.total > 0 THEN 'Completed'
    WHEN DATE(DRI.timestamp) < DATE(NOW()) AND DRI.total = 0 THEN 'Overdue'
    WHEN DATE(DRI.timestamp) >= DATE(NOW()) THEN
        CASE
            WHEN DRI.total = 0 THEN 'Pending'
            WHEN DRI.total > 0 THEN 'Prepaid'
        END     
END AS payment_status,
DATE_FORMAT(DRI.timestamp, '%d-%m-%Y %H:%i:%s') AS 'stamp'
FROM drives DRI
LEFT JOIN clients CI ON DRI.client = CI.id
LEFT JOIN drivers DI ON DRI.driver = DI.id,
LEFT JOIN vehicles VI ON DRI.vehicle = VI.id
WHERE
DRI.user = '146'
ORDER BY DRI.id ASC