0

我正在使用 SQL 2008 并且遇到了问题。

我有 3 个不同的表,这是我的代码示例。

SELECT DISTINCT Name Age
FROM Table1
LEFT JOIN Table2
ON Table1.ID = Table2.ID

这将返回如下内容:

Name Age
tom   12
ben   23
ian   12 

我有另一个问题

SELECT Name
FROM Table3

这将返回:

ian   12 
ian   12
ian   12

我想验证如果名称和年龄在第一个查询的名称中并且在第二个查询 Table3.name 中,它将返回如下内容:

ian   12 
ian   12
ian   12

我一直在这两列上尝试加入和联合,但到目前为止只能让它返回。有什么建议么?

ian   12
4

2 回答 2

2

首先,您说出您的问题-您想要获取所有记录,这些记录的组合NameAge存在于不同的记录集中NameAge来自连接的记录集中。然后你使用声明性语言的力量和一点CTE来获得你的解决方案:

;with CTE as (
    select distinct Name, Age
    from Table1 as T1
        inner join Table2 as T2 on T2.ID = T1.ID
)
select *
from Table3 as T3
where exists (select * from CTE as C where C.Name = T3.Name and C.Age = T3.Age)

SQL FIDDLE 示例来摆弄查询

于 2013-08-02T03:19:12.427 回答
2

This might be able to be simplified (need to see your table structures and sample data), but given your queries, a subquery should work for you:

SELECT T3.Name, T3.Age
FROM Table3 T3
    JOIN (
        SELECT DISTINCT Name, Age
        FROM Table1
            LEFT JOIN Table2
                ON Table1.ID = Table2.ID
    ) T ON T3.Name = T.Name AND T3.Age = T.Age
于 2013-08-01T22:31:43.290 回答