****编辑**** 在此处添加 SQL Fiddle 链接 我在 SQL Fiddle 中创建了场景以显示我想要完成的任务。我发现它在 SQL Fiddle 中产生准确的结果但使用我的数据库产生以下结果非常奇怪。
然而,为了证明这里确实存在这些季节,我们选择了 tvseasons 加入 tvseries:
运行此查询:
SELECT TVSeriesHasTVSeason.tvSeriesID, TVSeason.tvSeasonID, TVSeason.title, Users.userID,
CASE
WHEN UserHasWatchedTVSeason.tvSeasonID IS NULL THEN 'No'
ELSE 'Yes'
END as watched
FROM TVSeason
CROSS JOIN Users
LEFT JOIN UserHasWatchedTVSeason
ON TVSeason.tvSeasonID = UserHasWatchedTVSeason.tvSeasonID
AND Users.userID = UserHasWatchedTVSeason.userID
RIGHT JOIN TVSeriesHasTVSeason
ON TVSeason.tvSeasonID = TVSeriesHasTVSeason.tvSeasonID
回报:
515 1769 1000 Ways to Die Season 1 3 Yes
515 1770 1000 Ways to Die Season 2 3 Yes
515 1772 1000 Ways to Die Season 4 3 Yes
515 1773 1000 Ways to Die Season 5 3 Yes
516 1774 2 Stupid Dogs Season 1 3 No
516 1775 2 Stupid Dogs Season 2 3 No
517 1777 24 Season 2 3 Yes
517 1779 24 Season 4 3 Yes
517 1780 24 Season 5 3 Yes
517 1781 24 Season 6 3 Yes
517 1782 24 Season 7 3 Yes
赛季id是连续的,你可以清楚地看到1000种死法的第3季没有被归还,还有几个24季也没有被归还。
我不知道这个查询有什么问题?
****编辑**我相信我找到了解决该问题的有效方法:**
SELECT x.*,
CASE
WHEN UserHasWatchedTVSeason.tvSeasonID IS NULL THEN 'No'
ELSE 'Yes'
END as watched
FROM
(SELECT
TVSeries.tvSeriesID, TVSeries.title,
TVSeriesHasTVSeason.tvSeasonID,
Users.userID
FROM TVSeries
LEFT JOIN TVSeriesHasTVSeason
on tvseries.tvSeriesID = TVSeriesHasTVSeason.tvSeriesID
LEFT JOIN TVSeason
on tvseason.tvSeasonID = TVSeriesHasTVSeason.tvSeriesID
CROSS JOIN Users)x
LEFT JOIN UserHasWatchedTVSeason
on x.tvSeasonID = UserHasWatchedTVSeason.tvSeasonID
AND x.userID = UserHasWatchedTVSeason.userID