我的电影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
它显示了13个结果,而不是数据库中的18个电影。我搜索了你的问题清单,但没有找到合适的答案。你能告诉我哪里出错了,还是有更好的方法来安排这个问题?
答案 0 :(得分:0)
更新 -
UNION
你出错了。它删除重复。你的内部查询正在返回(5,5,4,2,1,1,0),但是在删除重复项后,联合将它们转换为(5,4,2,1,0)。
您需要使用UNION ALL
来计算所有内容。只需将所有UNION
替换为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;