使用先前查询的数据

时间:2011-11-11 17:06:15

标签: sql sql-server-2008 subquery

我想使用像这样的查询

SELECT personId
FROM Person p 
Inner Join address a on p.personId=a.personId
WHERE(a.created > GETDATE() -10)

我想使用此数据来过滤此查询

SELECT * 
FROM accounts a
WHERE a.person /*is in the results of the previous query */

我该怎么做?

4 个答案:

答案 0 :(得分:3)

这应该可以解决问题(假设你的帐户表中有列personId)。

SELECT * 
FROM accounts a
WHERE a.personId in (
                SELECT DISTINCT personId
                FROM Person p 
                Inner Join address a on p.personId=a.personId
                WHERE(a.created > DATEADD(d,-10,GETDATE())))

或者,您可以直接加入3个表,而不是使用子查询:

SELECT
    C.*
FROM
    accounts C
INNER JOIN
    Person P ON P.personId = C.personId
INNER JOIN
    [Address] A ON A.personId = P.PersonId
WHERE
    A.created > DATEADD(d,-10,GETDATE())

答案 1 :(得分:3)

SQL Server 2008中的一个很好的功能是公用表表达式(CTE)。它基本上是一个内联视图,使实际返回数据的查询更加清晰。

WITH people
AS
(
SELECT personId
FROM Person p 
Inner Join address a on p.personId=a.personId
WHERE(a.created > GETDATE() -10)
)

SELECT * 
FROM accounts a
INNER JOIN people p ON a.personId = p.personId

答案 2 :(得分:1)

你可以这样做:

SELECT * 
FROM accounts a
WHERE a.person IN 
(
SELECT personId
FROM Person p 
Inner Join address a on p.personId=a.personId
WHERE(a.created > GETDATE() -10)
);

答案 3 :(得分:1)

begin
with Results AS
(
SELECT *
FROM Person p 
Inner Join address a on p.personId=a.personId
WHERE(a.created > GETDATE() -10)
)
END

SELECT * 
FROM accounts a
WHERE a.person IN (select person from Results )