在第二个查询sql中使用来自一个查询的值

时间:2015-01-07 21:56:34

标签: sql

SELECT AS, COUNT(*)
FROM Table1
HAVING COUNT(AS)>1
group BY AS;

这会产生结果

AS      COUNT
5       2

然后我想在另一个查询中使用AS值,只输出最终结果。这是可能的吗。我在想这样的事情。

SELECT * 
FROM 
TABLE 2 
Where AS =(
           SELECT AS, COUNT(*)
           FROM Table1
           HAVING COUNT(AS)>1
           group BY AS;
);

2 个答案:

答案 0 :(得分:1)

这称为子查询。为安全起见,您将使用in而不是=(并且as是列的错误名称,因为它是SQL关键字):

SELECT * 
FROM TABLE2 
WHERE col IN (SELECT col
              FROM Table1
              GROUP BY col
              HAVING COUNT(col) > 1
             );

您的第一个查询也不正确,因为having子句位于group by之后。

答案 1 :(得分:0)

您可以将子查询与in运算符一起使用:

SELECT *
FROM   table2
WHERE  AS IN (SELECT   AS
              FROM     table1
              GROUP BY AS
              HAVING   COUNT(*) > 1)