2012-02-15 27 views
0
select lastname, firstname 
    from person 
    group by lastname, firstname 
    having 50 >= 
       (select count(p.personid) from filmparticipation x, film f, person p 
       where f.filmid = x.filmid and 
       x.personid = p.personid and 
       x.parttype = 'cast' 
       ); 

簡短的介紹,這是基於電影數據庫。有了這個查詢,我應該得到超過50倍的電影中的演員。 要知道的細節,電影包含膠片,然後解析filmparticipation哪裏有一些與電影相關的角色。 p.personid包含姓氏和名字。 任何指導意見將preciated :)SQL計數器失敗

+1

它有什麼問題? – Blorgbeard 2012-02-15 17:15:37

+0

計數器根本不工作... – 2012-02-15 17:21:07

回答

1

你實際上並不需要film表查詢任何內容,所以你可以離開它ou噸。您還應該記住,演員可能在一部電影中擔任多個角色,因此可能會在filmparticipation表中的每部影片中擁有多個條目。爲了解決這個問題,請使用DISTINCT的子查詢。

SELECT lastname, firstname, COUNT(*) AS films 
FROM (SELECT DISTINCT p.lastname, p.firstname, f.filmid 
    FROM person p, filmparticipation f 
    WHERE p.personid = f.personid AND f.parttype = 'cast') p 
GROUP BY lastname, firstname 
HAVING films >= 50; 
+0

在PostgreSQL中,你不能說:HAVING films> = 50 – user265767 2013-03-06 15:23:34

2

給這個一杆。我相信,子查詢是多餘的:

select p.lastname, p.firstname, count(*) 
from person p 
join filmparticipation x on p.personid = x.personid 
join film f on x.filmid = f.filmid 
where x.parttype = 'cast' 
group by p.lastname, p.firstname 
having count(*) > 50 
0

(count) >= 50 

50 <= (count)