2

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

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

我将这 3 部加在一起,这样如果我有 3 部电影,每部有 3 种流派,我将得到 9 行。

现在我希望能够获得包含特定类型的电影(例如 ID 为 2 和 4 的电影),这仅在我使用一种类型时才有效,因为每一行只有一种类型。有人知道解决这个问题的方法吗?

所以如果我尝试

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

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

4

5 回答 5

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
于 2012-08-29T07:19:02.947 回答
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;
于 2012-08-29T07:23:45.083 回答
0

尝试在 sql 查询中给出 OR 而不是 AND。

于 2012-08-29T07:27:03.177 回答
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
于 2012-08-29T07:30:58.830 回答
0

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

SELECT tblmovie.movieName , tblgenre.genereName
FROM tblmoviegenre
WHERE tblmovie.id=tblmoviegenre.tblmovie_id AND tblgenre.id=tblmoviegenre.tblgenre_id
于 2012-08-29T07:31:06.950 回答