鉴于您的数据库结构,一个可能的解决方案是
SELECT rented.MOVIE_ID
,rented_movies_count
,available_movie_count
FROM (
SELECT MOVIE_ID, count(MOVIE_ID) AS rented_movies_count
FROM MOVIE_QUEUE
WHERE STATUS_ID=2
GROUP BY MOVIE_ID
) rented
,(SELECT MOVIE_ID, count(MOVIE_ID) AS available_movie_count
FROM dvd
GROUP BY MOVIE_ID
) available
WHERE rented.movie_id = available.movie_id
AND rented_movies_count >= available_movie_count
;
我在http://www.sqlfiddle.com/#!4/3fc59/11上设置了一个示例进行测试。但我想这或多或少是你想出的。
但我有点怀疑你的数据库结构真的是最优的!?movie_id
你真的在表中存储了多个记录dvd
吗?
将每张唱片与一些电影属性一起保存并将 DVD 的出租状态存储在movie_id
其中不是更有用吗?dvd
movie_queue.status_id
如果movie_queue.status_id
定义为说
- ...可用的
- ...租用
那么你的查询会容易得多:
SELECT MOVIE_ID
,count(case when status_id = 1 then 1 end) AS available_movie_count
,count(case when status_id = 2 then 1 end) AS rented_movies_count
FROM MOVIE_QUEUE
GROUP BY MOVIE_ID
HAVING count(case when status_id = 2 then 1 end) >= count(case when status_id = 1 then 1 end)
;
参见例如http://www.sqlfiddle.com/#!4/13739/1