我正在为此编写 sql 查询列出所有在犯罪 ID 10089 中涉及任何犯罪代码指控的罪犯的姓名问题陈述,但我的结果与或没有 where 条件
select *
from criminals c
join crimes cms
on c.criminal_id = cms.criminal_id
join crime_charges cc on cc.crime_id=cms.crime_id
order by c.first, c.last;
where (cc.fine_amount is not null) and (cc.crime_id==10089);
答案 0 :(得分:1)
在 order by 之前使用 where 条件并删除分号,因为它表示查询结束,因此 where 条件被视为单独的查询。
select *
from criminals c
join crimes cms
on c.criminal_id = cms.criminal_id
join crime_charges cc on cc.crime_id=cms.crime_id
where (cc.fine_amount is not null) and (cc.crime_id=10089)
order by c.first, c.last;
答案 1 :(得分:0)
这表明 exists
。但是,我认为一个关键的组成部分是确定给定费用是否也是 10089 的费用。窗口函数是一种方便的处理方式:
select c.*
from criminals c
where exists (select 1
from crimes cr join
(select cc.*,
sum(case when cc.crime_id = 10089 then 1 else 0 end) over (partition by cc.crime_charge) as num_10089
from crime_charges cc
) cc
on cr.crime_id = cc.crime_id
where c.criminal_id = cr.criminal_id
)
order by c.first, c.last;
注意:问题陈述没有提到罚款,所以我删除了那个逻辑。