1

我有几张电影 DVD,想在 MySQL 中创建一个简单的数据库。PF DB 结构。我有一个 MySQL 查询,它实际上没有列出确切的编号。我有的电影。下面的查询是 -

SELECT SUM(Total) as total
FROM (
SELECT COUNT(DISTINCT(Movie1)) AS Total FROM tbl_movie 
      WHERE Movie1 !='' AND Movie1 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie2)) FROM tbl_movie 
       WHERE Movie2 !='' AND Movie2 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie3)) FROM tbl_movie 
       WHERE Movie3 !='' AND Movie3 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie4)) FROM tbl_movie 
       WHERE Movie4 !='' AND Movie4 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie5)) FROM tbl_movie 
       WHERE Movie5 !='' AND Movie5 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie6)) FROM tbl_movie 
       WHERE Movie6 !='' AND Movie6 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT COUNT(DISTINCT(Movie7)) FROM tbl_movie 
       WHERE Movie7 !='' AND Movie7 IS NOT NULL AND DVDCategory='Movie'
) AS Total;

数据库结构 -

ID DVD Movie1   Movie2   Movie3      Movie4          Movie5   Movie6   Movie7
__________________________________________________________________
1  1  IronMan  Movie11   MindHunters  300            Jumper   7        
2  2  IronMan2 Movie22   Grey         Blood Diamond
3  3  Movie33  Red Eye   Departed     300            
4  4  Movie44  Gladiator King Kong
5  5  Movie55  Hitman

它在 DB 中显示 13 个结果而不是 18 个电影。我搜索了您的问题列表,但没有找到任何合适的答案。你能告诉我哪里出错了,或者有什么更好的方法可以安排这个查询吗?

4

1 回答 1

0

更新 -

你错了UNION。它删除重复项。您的内部查询正在返回 (5,5,4,2,1,1,0) 但在删除重复项后联合将它们变为 (5,4,2,1,0)。

您需要使用UNION ALL来计算所有内容。只需将所有UNIONs替换为UNION ALL

当您这样做时,您会注意到如果有跨列的电影,即如果电影 300 在列中Movie4并且Movie5针对不同的用户,它将计算两次。

如果您只需要在所有列中获取不同的电影,请先从各个列中获取不同的电影,UNION然后删除重复项,然后对电影进行计数。

SELECT COUNT(movie) as total
FROM (
SELECT DISTINCT Movie1 AS movie FROM tbl_movie 
    WHERE Movie1 !='' AND Movie1 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie2 FROM tbl_movie 
    WHERE Movie2 !='' AND Movie2 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie3 FROM tbl_movie 
     WHERE Movie3 !='' AND Movie3 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie4 FROM tbl_movie 
     WHERE Movie4 !='' AND Movie4 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie5 FROM tbl_movie 
     WHERE Movie5 !='' AND Movie5 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie6 FROM tbl_movie 
     WHERE Movie6 !='' AND Movie6 IS NOT NULL AND DVDCategory='Movie'
UNION
SELECT DISTINCT Movie7 FROM tbl_movie 
     WHERE Movie7 !='' AND Movie7 IS NOT NULL AND DVDCategory='Movie'
) AS AllDistinctMovies;
于 2013-09-17T16:11:05.873 回答