如何选择另一个表中不存在的值?

问题描述 投票:0回答:2

所以我有2张桌子fee_types,包含所有费用类型

+-------------+---------------+
| fee_type_id | fee_type_name |
+-------------+---------------+
|           1 | Caution Fee   |
|           2 | Lab Fee       |
|           3 | Admission Fee |
|           4 | Term Fee I    |
|           5 | Term Fee II   |
|           6 | Computer Fee  |
+-------------+---------------+

paid_fees,包括学生已支付的费用

+--------------+------------+-------------+---------------+
| student_name | student_id | fee_type_id | fee_type_name |
+--------------+------------+-------------+---------------+
| ABC          |       4601 |           1 | Caution Fee   |
| ABC          |       4601 |           2 | Lab Fee       |
| ABC          |       4601 |           4 | Term Fee I    |
| ABC          |       4601 |           5 | Term Fee II   |
| XYZ          |       4602 |           3 | Admission Fee |
| XYZ          |       4602 |           1 | Caution Fee   |
| XYZ          |       4602 |           2 | Lab Fee       |
| XYZ          |       4602 |           4 | Term Fee I    |
| XYZ          |       4602 |           6 | Computer Fee  |
+--------------+------------+-------------+---------------+

现在,我想显示学生未支付的费用类型。例如,学生ABC尚未支付AdmissionComputer费用,而学生XYZ尚未支付Term II费用。我希望结果表看起来像这样

+--------------+------------+-------------+---------------+
| student_name | student_id | fee_type_id | fee_type_name |
+--------------+------------+-------------+---------------+
| ABC          |       4601 |           1 | Admission Fee |
| ABC          |       4601 |           2 | Computer Fee  |
| XYZ          |       4602 |           3 | Term II       |
+--------------+------------+-------------+---------------+

我该怎么做?我已经尝试了StackOverflow的几种解决方案,但是都没有用。有人可以建议我该怎么办?

mysql sql join select
2个回答
2
投票

您可以将学生名单与可能的费用列表交叉加入,然后使用not exists展示未出现在paid_fees中的那些:

select s.*, f.*
from (select distinct student_name, student_id from paid_fees) s
cross join fee_types f
where not exists(
    select 1 
    from paid_fees pf 
    where pf.student_id = s.student_id and pf.fee_type_id = f.fee_type_id
)

在现实生活中,您将有一个单独的表来存储学生,可以在select distint子查询中使用它:

select s.*, f.*
from students s
cross join fee_types f
where not exists(
    select 1 
    from paid_fees pf 
    where pf.student_id = s.student_id and pf.fee_type_id = f.fee_type_id
)

0
投票

选择s.student_name,s.student_id,f.fee_type_id,f.fee_type_name从paid_fees作为pf交叉加入费率类型为f交叉加入学生除了选择s.student_name,s.student_id,f.fee_type_id,f.fee_type_name从paid_fees作为pf内部联接fee_types作为pf.fee_type_id = f.fee_type_id上​​的f在pf.student_id = s.student_id上以s身份加入内部学生

© www.soinside.com 2019 - 2024. All rights reserved.