我坚持使用SQL查询。我知道要做什么,但我无法弄明白如何。 所以,这是所需的方案:
电影(标题,导演,年份,类型,费率);
TITLE DIRECTOR YEAR GENRE RATE
Fight club Fincher 1999 Action 4.5
Vertigo Hitchock 1958 Drama 5
Donnie darko Kelly 2001 Thriller 3.5
视频(标题,导演, colloc );
TITLE DIRECTOR COLLOC
Fight club Fincher 3877
Fight club Fincher 3878
Vertigo Hitchcock 5431
Vertigo Hitchcock 5432
Donnie darko Kelly 9986
租( colloc , dateRent ,customer,dateReturn);
COLLOC DATERENT CUSTOMER DATERETURN
3877 2016-05-02 324 2016-05-04
3877 2016-05-20 365 2016-05-20
3878 2016-04-11 876 2016-04-12
3878 2016-06-06 112 2016-06-08
... ... ... ...
... ... ... ...
9986 2016-02-24 443 2016-02-28
以下是查询:
为每部电影列出至少两次租借的视频数量。
(注意:商店通常有更多视频 - dvds,vhs等 - 每部电影都有。)
我的方法如下:我将从这个简单的查询开始
SELECT colloc, title, director, COUNT(colloc) AS rentNumber
FROM Rent
NATURAL JOIN Video
GROUP BY colloc
显示如下内容:
COLLOC TITLE DIRECTOR RENTNUMBER
3877 Fight club Fincher 2
3878 Fight club Fincher 2
5432 Vertigo Hitchcock 2
5431 Vertigo Hitchcock 1
9986 Donnie darko Kelly 1
为了达到这个目的:
TITLE DIRECTOR VIDEOSNUMBER
Fight club Fincher 2
Vertigo Hitchcock 1
Donnie darko Kelly 0
但是我错过了最后一步,我无法正确使用GROUP BY / HAVING。 即使使用子查询也没有成功。 我一直试图采用不同的方法,但我没有任何好处,所以任何提示都会受到赞赏。
感谢。
编辑:注意,不需要在查询中使用表格Movie。我把它放在那里只是为了解释一部电影可以有多个视频。 添加了表格示例。主键以粗体显示。
解: 由于你的提示,我找到了一个解决方案(说实话,它是部分的,因为它让所有没有视频出租至少2次的电影放出)。 无论如何,这是:
SELECT title, director, COUNT(title) AS videosNumber
FROM (SELECT colloc, title, director, COUNT(colloc) AS rentNumber
FROM rent NATURAL JOIN video
GROUP BY colloc
) X
WHERE rentNumber > 1
GROUP BY title
答案 0 :(得分:1)
尝试此查询:
VirtualHost
答案 1 :(得分:0)
试试这个
SELECT
-- if you want to add colloc, uncomment below
-- r.colloc as COLLOC
m.title as TITLE,
m.director as DIRECTOR,
COUNT(r.colloc) as VIDEOSNUMBER
FROM movie m
LEFT JOIN video v ON m.title = v.title
LEFT JOIN rent r ON v.colloc = r.colloc
GROUP BY TITLE
答案 2 :(得分:0)
测试了它:
SELECT m.TITLE, m.DIRECTOR, COALESCE(rs.Rentnumber, 0) AS VIDEOSNUMBER
FROM Movie AS m
LEFT JOIN
(
SELECT
--r.colloc, -- if you want to see r.colloc
v.TITLE,
v.DIRECTOR,
COUNT(v.TITLE) AS Rentnumber
FROM Video AS v
LEFT JOIN Rent as r on v.colloc = r.colloc
GROUP BY r.colloc, v.TITLE, v.DIRECTOR
) AS rs ON m.title = rs.title AND m.director = rs.director
Group by m.title, m.director
答案 3 :(得分:0)
尝试下面的脚本。
您应该在SELECT
子句中的GROUP BY
列表中包含这些列。
SELECT TITLE,DIRECTOR,MIN(VIDEOSNUMBER) VIDEOSNUMBER
FROM (
SELECT v.colloc,v.TITLE,v.DIRECTOR ,COUNT( r.colloc) VIDEOSNUMBER
FROM Video v
LEFT JOIN Rent r on v.colloc=r.colloc
GROUP BY v.TITLE,v.DIRECTOR,v.colloc)t
GROUP BY TITLE,DIRECTOR