我是 SQL 初学者。我有两个表,一个是student_records,另一个是student_fees表,其中存在折扣费用(fee_type_code=2)和常规费用(fee_type_code=1)学生的记录。费用类型的代码是fee_type_code。由于系统存在错误,一些学生同时获得了两种费用类型。我想获取所有的错误记录。首先,我有两个查询可以单独正常工作,但我尝试将它们合并到一个查询中,然后在临时表上创建联接:
select
student_id, fee_type_code
from
((select * from student_records r, student_fees f
where s.student_id=f.student_id and fee_type_code=1) A
inner join
(select * from student_records r, student_fees f
where
s.student_id=f.student_id and fee_type_code=2) B
on A.student_id=B.student_id);
对于给您带来的任何不便,或者如果这个问题太天真,我深表歉意,但我陷入了困境。我收到的错误是“对student_id的引用不明确...”
最佳答案
如果您的目标是获取具有两种费用类型的学生列表,那么您可以使用 group by
和 having
来代替:
select sr.student_id
from student_records sr
join student_fees sf on sr.student_id = sf.student_id
where sf.fee_type_code in (1,2)
group by sr.student_id
having count(distinct sf.fee_type_code) = 2
关于两个相似子查询之间的sql连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34359821/