mysql查询中的错误答案

hivapdat  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(368)

我的问题是“统计每年只有女性演员的电影数量”。
表架构如下:

--------------------   -----------------------   ----------------------
|       Movie      |   |     Person           |  |       Cast         |
--------------------   ------------------------  ----------------------
| MID    |   year  |   |  PID     |   Gender  |  |    MID   |    PID  |
--------------------   ------------------------  ----------------------

我编写了以下mysql查询:

SELECT m.year, COUNT(m.MID) AS Movies_Female FROM Movie m
        WHERE m.MID IN ( SELECT Q.MID FROM ( SELECT m_c.MID, COUNT(m_c.PID) AS No_Actors FROM M_Cast m_c GROUP BY m_c.MID) Q 
        WHERE Q.No_Actors = ( SELECT COUNT(m__c.PID) FROM M_Cast m__c JOIN PERSON p 
        ON TRIM(p.PID) = TRIM(m__c.PID)
        WHERE m__c.MID = Q.MID AND TRIM(p.Gender) = 'Female')) GROUP BY m.year

但是我得到的结果是:

year    Movies_Female
0   1939        1
1   1999        1
2   2000        1
3   2009        1
4   2012        1
5   2018        1

但是,当我手动检查2009年和2012年没有任何电影只有女性演员。请解决我的查询哪里出错了?

q5iwbnjs

q5iwbnjs1#

你可以用 not exists 要筛选出至少有一个非女性演员的电影:

select m.year, count(*) as movies_female 
from movie m
where not exists (
    select 1 
    from cast c
    inner join person p on p.pid = c.pid
    where c.mid = m.mid and p.gender <> 'Female'
)
group by m.year

这假设每个电影中至少有一个条目 cast (这似乎是一个合理的假设)。

相关问题