简体   繁体   中英

MySQL not selecting row if foreign key column has NULL value

The following SQL works, but if a row has transfers.driver as NULL , that row won't be selected. Once I add a value in for driver that row will be selected. How can I select the row even if driver is NULL ?

SELECT 
    transfers.id, 
    transfers.name AS name, 
    transfers.pickup_time AS pickup_time, 
    transfers.voucher AS voucher, 
    transfer_types.name AS type, 
    drivers.name AS driver 
FROM
    transfers 
INNER JOIN transfer_types ON transfer_types.id = transfers.type 
INNER JOIN drivers ON drivers.id = transfers.driver

Here's the structure of the table:

CREATE TABLE `transfers` (
  `id` int(10) UNSIGNED NOT NULL,
  `voucher` varchar(24) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `type` int(10) UNSIGNED DEFAULT NULL,
  `pickup_time` time DEFAULT NULL,
  `name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `driver` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

And here's the foreign keys:

ALTER TABLE `transfers`
  ADD CONSTRAINT `transfers_driver_foreign` 
      FOREIGN KEY (`driver`) REFERENCES `drivers` (`id`),
  ADD CONSTRAINT `transfers_type_foreign` 
      FOREIGN KEY (`type`) REFERENCES `transfer_types` (`id`);

use left join instead of inner join :

SELECT 
    transfers.id, 
    transfers.name AS name, 
    transfers.pickup_time AS pickup_time, 
    transfers.voucher AS voucher, 
    transfer_types.name AS type, 
    drivers.name AS driver 
FROM
    transfers 
LEFT JOIN transfer_types ON transfer_types.id = transfers.type 
LEFT JOIN drivers ON drivers.id = transfers.driver

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM