如果在一个表中显示多个SQL查询,则显示其他表数据

时间:2013-02-25 01:53:02

标签: sql

当PropertyID在Property中出现多次时,我试图从Owner中获取OwnerID,FName,LName。这是我尝试过但我对sql很新的所以我不知道这是否接近。

Select OwnerID, FName, LName 
From Owner 
Where OwnerID = (Select OwnerID 
                 From Property 
                 GROUP BY OwnerID 
                 HAVING Count(*) >=2)

3 个答案:

答案 0 :(得分:2)

你的意思是:

Select OwnerID, FName, LName 
From Owner 
Where OwnerID In (Select OwnerID 
                 From Property 
                 Group By OwnerID 
                 Having Count(OwnerId) >= 2)

但是如果你想让所有拥有超过1个财产的所有者,那就假设一个财产总是只有一个所有者,而现实世界并不总是如此。

答案 1 :(得分:2)

你可以像@Mitch Wheat一样使用IN运算符,或使用EXISTS:

Select OwnerID, FName, LName 
From Owner a
Where EXISTS (Select b.OwnerID 
                 From Property b
                 WHERE a.OwnerID = b.OwnerID
                 Group By b.OwnerID 
                 Having Count(b.OwnerId) >= 2)

答案 2 :(得分:1)

按性能我会做

Select OwnerID, FName, LName 
From Owner a
Where EXISTS (Select *
             From Property b
             WHERE a.OwnerID = b.OwnerID
             Group By b.OwnerID 
             Having Count(*) >= 2)