连接多个表时出现“WHERE”问题

时间:2012-08-29 07:15:09

标签: mysql sql

我在查询时遇到了一些麻烦。

我正在建立一个电影数据库,它有3个表格。 1个用于电影(tblmovie),1个用于流派(tblgenre),1个用于连接这些2个(tblmoviegenre)。

我将这3个连在一起,所以如果我有3部电影各有3个类型,我会得到9行。

现在我希望能够获得包含某些类型的电影(例如ID为2和4的电影),这只适用于我使用一种类型的电影,因为每行只有1种类型。有人知道为此工作吗?

所以,如果我尝试

SELECT tblmovie.name as moviename 
FROM tblmovie as m
LEFT JOIN tblmoviegenre as mg
on m.movieID = mg.movieID
LEFT JOIN tblgenre as g
on mg.genreID = g.genreID
WHERE mg.genreID = 2 
AND mg.genreID = 4

我没有得到任何结果,因为每行只有1种类型。

5 个答案:

答案 0 :(得分:3)

尝试这样的事情,

SELECT  movieName
FROM    tableName a       -- of course you need to provide joins here
WHERE   genreID IN (2,4)
GROUP BY movieName
HAVING COUNT(*) = 2

这里的想法是将实例数量与您提供的类型总数相匹配。

更新1

SELECT tblmovie.name as moviename 
FROM tblmovie as m
          LEFT JOIN tblmoviegenre as mg
               on m.movieID = mg.movieID
          LEFT JOIN tblgenre as g
               on mg.genreID = g.genreID
WHERE mg.genreID IN (2,4) 
GROUP BY tblmovie.name
HAVING COUNT(*) = 2

答案 1 :(得分:1)

使用IN子句代替AND子句:

SELECT tblmovie.name as moviename 
FROM tblmovie as m
     LEFT JOIN tblmoviegenre as mg
          ON m.movieID = mg.movieID
     LEFT JOIN tblgenre as g
          ON mg.genreID = g.genreID
WHERE mg.genreID IN(2,4)
GROUP BY tblmovie.name
HAVING COUNT(DISTINCT genreID) = 2;

答案 2 :(得分:0)

尝试在sql查询中使用OR代替AND。

答案 3 :(得分:0)

试一试:

SELECT tblmovie.name as moviename 
FROM tblmovie as m
LEFT JOIN tblmoviegenre as mg on m.movieID = mg.movieID
                              and mg.genreID in(2,4) 
LEFT JOIN tblgenre as g       on  mg.genreID = g.genreID

答案 4 :(得分:0)

我认为以下查询将适用于此情况。

SELECT tblmovie.movieName , tblgenre.genereName
FROM tblmoviegenre
WHERE tblmovie.id=tblmoviegenre.tblmovie_id AND tblgenre.id=tblmoviegenre.tblgenre_id