联接和可为空的值

Join and nullable values

我的 MySql 数据库中有三个表:

车辆

用户

合作者

我想创建一个连接这三个表的视图,所以我试试这个

select Id_vehicle_pk, id_driver_fk,mail, Id_coll_pk, First_Name,Last_Name
from 
  Vehicle join User join 
  Collaborator 
where 
  `Vehicle`.`id_driver_fk` = `User`.`Id_user_pk` 
  and `Collaborator`.`Id_user_fk` = `User`.`Id_user_pk`
group by Id_vehicle_pk
Having Id_vehicle_pk> 0

但由于 id_driver_fk 的空值,我得到了错误的结果。所以我需要知道 :

  1. 如何解决我的查询?

您的两个联接中都缺少 on 子句。

select Id_vehicle_pk, 
       id_driver_fk, 
       mail, Id_coll_pk, 
       First_Name,
       Last_Name
from Vehicle 
join User on id_driver_fk = Id_user_pk
join Collaborator on Id_user_pk = Id_user_fk
group by Id_vehicle_pk
Having Id_vehicle_pk> 0

我认为您正在寻找 LEFT JOIN 子句,它允许从主 table 获取所有记录,即使没有与其他 table 的外键匹配:

SELECT 
     v.Id_vehicle_pk, 
     v.id_driver_fk, 
     u.mail,  
     c.Id_coll_pk, 
     c.First_Name,  
     c.Last_Name
FROM Vehicle v LEFT JOIN 
     User u ON v.id_driver_fk  = u.Id_user_pk LEFT JOIN
     Collaborator c ON c.Id_user_fk = u.Id_user_pk
WHERE Id_vehicle_pk> 0

此外,最好将连接条件放在连接中而不是 WHERE 子句中。