如何将查询包含到另一个查询中?

时间:2014-03-27 12:37:09

标签: sql-server

我正在尝试指定两部电影的名称,并获得一起看过这些两部电影的人数的总数,内部选择工作正常并给出了数据库中所有电影的总结果但当我试图把外部选择只指定两部电影我得到语法错误,任何帮助,请?

 SELECT t.movie1,
        t.movie2,
        t.count 
 FROM t
 (SELECT I.Movie movie1,
         J.Movie movie2, 
         COUNT(I.CustomerId) count
 FROM Movies I, 
      Movies J 
 WHERE I.CustomerID = J.CustomerID 
       AND I.Movie < J.Movie
 GROUP BY I.Movie, 
          J.Movie
 HAVING COUNT(I.CustomerID) >= 150) as t
 WHERE movie1 LIKE 'Star Wars Episode II: Attack of the Clones' 
       AND movie2 LIKE 'Star Wars Episode V: Empire Strikes Back';

2 个答案:

答案 0 :(得分:0)

不要指定别名两次;在将内部查询识别为t之前从t中选择。

SELECT  t.movie1
      , t.movie2
      , t.count
FROM    ( SELECT    I.Movie movie1
                  , J.Movie movie2
                  , COUNT(I.CustomerId) count
          FROM      Movies I
                    JOIN Movies J ON I.CustomerID = J.CustomerID
                                     AND I.Movie < J.Movie
          GROUP BY  I.Movie
                  , J.Movie
          HAVING    COUNT(I.CustomerID) >= 150
        ) AS t
WHERE   movie1 LIKE 'Star Wars Episode II: Attack of the Clones'
        AND movie2 LIKE 'Star Wars Episode V: Empire Strikes Back';

答案 1 :(得分:0)

您的内部查询没问题,但您实际上并未在外部查询中指定表。可视化的最佳方法是想象括号内的所有内容都是一个表名。这是你写的:

 SELECT t.movie1,
        t.movie2,
        t.count 
 FROM t
 t as t
 WHERE movie1 LIKE 'Star Wars Episode II: Attack of the Clones' 
       AND movie2 LIKE 'Star Wars Episode V: Empire Strikes Back';

有时当你在使用这样的连接时,使用#tmp表更容易将查询分解为两个查询。

DECLARE @MovieName1 VARCHAR(500)
DECLARE @MovieName2 VARCHAR(500)
SET @MovieName1 = 'IT'
SET @MovieName2 = 'The Fly'

SELECT
    a.CustomerID,
INTO 
    #Movie1Users
FROM 
    Movies a
WHERE a.MovieName = @MovieName1

SELECT
    a.customerID,
    @MovieName1,
    @MovieName2,
    COUNT(*) AS CustomerCount
FROM 
    Movies a
    INNER JOIN #Movie1Users b ON a.customerID = b.CustomerID
WHERE 
    a.MovieName = @MovieName2

Drop table #Movie1Users

然后,更容易看到它如何作为一个查询工作。 (我更喜欢保持内部查询别名不同以避免混淆)。希望我的下面的语法可以帮助您将来的查询。

DECLARE @MovieName1 VARCHAR(500)
DECLARE @MovieName2 VARCHAR(500)
SET @MovieName1 = 'IT'
SET @MovieName2 = 'The Fly'

SELECT
    @MovieName1,
    @MovieName2,
    COUNT(*) AS CustomerCount
FROM 
    Movies a
    INNER JOIN (
        SELECT
            z.CustomerID
        FROM 
            Movies z
        WHERE z.MovieName = @MovieName1
    )  b ON a.customerID = b.CustomerID
WHERE 
    a.MovieName = @MovieName2

最后,可以在没有子查询的情况下编写查询:

DECLARE @MovieName1 VARCHAR(500)
DECLARE @MovieName2 VARCHAR(500)
SET @MovieName1 = 'IT'
SET @MovieName2 = 'The Fly'

SELECT 
    @MovieName1 AS Movie1,
    @MovieName2 AS Movie2,
    (COUNT(*)/2) AS CustomerCount
FROM dbo.Movies a
INNER JOIN movies b ON a.CustomerID = b.CustomerID
WHERE
    (a.MovieName = @MovieName1 AND b.MovieName = @MovieName2)
    OR (a.MovieName = @MovieName2 AND b.MovieName = @MovieName1)
GROUP BY a.CustomerID