从一个表中选择值,其中另一个=值?

时间:2012-02-12 14:48:45

标签: sql sql-server sql-server-2005 select subquery

我正在尝试运行一个SQL查询(SQL Server),它将从子查询中查找名称列表。

我有这个,但我得到一个“子查询返回超过1”的错误:

SELECT FirstName + ' ' + LastName AS Name
FROM Members
WHERE     
   (MemberGUID = (SELECT ClassDetails.Leader
                  FROM Members AS Members_1 
                  INNER JOIN MemberDetails ON Members_1.MemberGUID = MemberDetails.Member 
                  INNER JOIN ClassDetails ON ClassDetails.Class = Members_1.CurrentClass
                  WHERE      
                      (MemberDetails.JoiningDate >= '02/03/2012') 
                      AND (Members_1.FirstName = '*') 
                      OR (MemberDetails.JoiningDate >= '02/03/2012') 
                      AND (Members_1.LastName = '*') 
                      OR (MemberDetails.JoiningDate >= '02/03/2012') 
                      AND (MemberDetails.Email IS NULL) 
                      AND (MemberDetails.MobilePhone IS NULL) 
                      AND (MemberDetails.WorkPhone IS NULL) 
                      AND (MemberDetails.HomePhone IS NULL) 
                      AND (Members_1.CurrentClass <> 339) 
                      AND (Members_1.CurrentClass <> 696) 
                      AND (Members_1.CurrentClass <> 0)))

我需要为子查询中返回的每个值返回值FirstNameLastName。 (子查询返回一个GUID列表,应该将其输入WHERE MemberGUID语句)

如何做到这一点?

4 个答案:

答案 0 :(得分:2)

使用in代替=

...
WHERE (MemberGUID in ( ... ))

您也可以将其设为连接而不是使用子查询:

SELECT FirstName + ' ' + LastName AS Name
FROM Members m1
INNER JOIN Members AS Members_1 ON m1.MemberGUID = ClassDetails.Leader
...

答案 1 :(得分:1)

副手,我认为您可以将MemberGUID =更改为MemberGUID IN

正如错误消息所述,您的子查询返回了许多行,并且您无法将单个值与多行的集合进行比较。但是可以在这些行中查找值,这正是IN运算符的作用。

MSDN Reference

答案 2 :(得分:1)

记住ANY, SOMEALL存在的好地方:

WHERE MemberGUID = ANY ( ... )

答案 3 :(得分:1)

在子查询中添加DISTINCT

SELECT FirstName + ' ' + LastName AS Name
FROM Members
WHERE MemberGUID IN 
       (SELECT DISTINCT ClassDetails.Leader
        FROM Members AS Members_1 INNER JOIN MemberDetails 
                  ON Members_1.MemberGUID = MemberDetails.Member 
             INNER JOIN ClassDetails 
                 ON ClassDetails.Class = Members_1.CurrentClass
        WHERE    (MemberDetails.JoiningDate >= '02/03/2012') 
                      AND (Members_1.FirstName = '*') 
                      OR (MemberDetails.JoiningDate >= '02/03/2012') 
                      AND (Members_1.LastName = '*') 
                      OR (MemberDetails.JoiningDate >= '02/03/2012') 
                      AND (MemberDetails.Email IS NULL) 
                      AND (MemberDetails.MobilePhone IS NULL) 
                      AND (MemberDetails.WorkPhone IS NULL) 
                      AND (MemberDetails.HomePhone IS NULL) 
                      AND (Members_1.CurrentClass <> 339) 
                      AND (Members_1.CurrentClass <> 696) 
                      AND (Members_1.CurrentClass <> 0)))