我有3张桌子:
list_routes
pk_route_id route_code route_name route_description
3 J1 IND IND-DPS
4 J4 ADT ADT_DPS
tbl_stu_route
pk_stu_route_id fk_stu_cls_id fk_route_id
2 13 3
tbl_stu_class
pk_stu_cls_id fk_stu_id
13 56
现在我想要实现的是在MYSQL中写入查询,它将从list_routes获取记录,这些记录没有关联或附加在tbl_stu_class中,因此,例如在上面的场景中它应该给我输出:
pk_route_id route_code route_name route_description
4 J4 ADT ADT_DPS
我使用左外连接编写了以下查询
SELECT
a.pk_route_id,
a.route_code,
a.route_name,
a.route_description
FROM
list_routes a
left outer join tbl_stu_route b on a.pk_route_id=b.fk_route_id
left outer join tbl_stu_class c on b.fk_stu_cls_id=c.pk_stu_cls_id
where c.fk_stu_id ='56'
但输出是
pk_route_id route_code route_name route_description
3 J1 IND IND-DPS
我不确定我哪里出错了。能否请你告诉我如何解决这个问题?
答案 0 :(得分:2)
如果您想获取 not exist 记录,请使用IS NULL
过滤掉
SELECT a.*
FROM list_routes a
left outer join tbl_stu_route b on a.pk_route_id=b.fk_route_id
left outer join tbl_stu_class c on b.fk_stu_cls_id=c.pk_stu_cls_id
where b.fk_route_id is null;
答案 1 :(得分:0)
鉴于问题的性质,我会使用not exists
:
SELECT lr.*
FROM list_routes lr
WHERE NOT EXISTS (SELECT 1
FROM tbl_stu_route sr JOIN
tbl_stu_class c
ON sr.fk_stu_cls_id = c.pk_stu_cls_id
WHERE lr.pk_route_id = sr.fk_route_id AND
c.fk_stu_id = 56
);
注意:
56
而不是'56'
。NOT EXISTS
比LEFT JOIN
更适合您的问题描述,但两者都有效。