我的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
的空值导致错误的结果。所以我需要知道:
答案 0 :(得分:1)
我认为您正在寻找允许从主表中获取所有记录的LEFT JOIN
子句,即使没有与其他表的外键匹配:
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
子句中。
答案 1 :(得分:0)
您错过了两个联接中的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