联接和可为空的值
Join and nullable values
我的 MySql
数据库中有三个表:
车辆
- Id_vehicle_pk(整数,自增,pk)
- id_driver_fk(varchar,fk, 可为空)
用户
- Id_user_pk(varchar,pk)
- 邮件(可变字符)
合作者
- Id_coll_pk(int,pk)
- Id_user_fk(varchar,fk)
- First_Name(varchar)
- Last_Name(varchar)
我想创建一个连接这三个表的视图,所以我试试这个
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
的空值,我得到了错误的结果。所以我需要知道 :
- 如何解决我的查询?
您的两个联接中都缺少 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
子句中。
我的 MySql
数据库中有三个表:
车辆
- Id_vehicle_pk(整数,自增,pk)
- id_driver_fk(varchar,fk, 可为空)
用户
- Id_user_pk(varchar,pk)
- 邮件(可变字符)
合作者
- Id_coll_pk(int,pk)
- Id_user_fk(varchar,fk)
- First_Name(varchar)
- Last_Name(varchar)
我想创建一个连接这三个表的视图,所以我试试这个
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
的空值,我得到了错误的结果。所以我需要知道 :
- 如何解决我的查询?
您的两个联接中都缺少 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
子句中。