我收到一个错误 - 子查询返回超过1的值。我的查询有什么问题

时间:2016-06-17 11:32:06

标签: sql-server

我的查询有什么问题。它给出了一个错误

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

Select top 1 name, 
            email, 
            [password]
FROM [MyPeople_DataVersion2].[dbo].[user] 
WHERE id = (
    Select userid 
    FROM [MyPeople_DataVersion2].[dbo].[EmployerUser] 
    WHERE empusertype=1 and employerid=96
    )

3 个答案:

答案 0 :(得分:2)

您的查询

Select userid 
FROM [MyPeople_DataVersion2].[dbo].[EmployerUser] 
WHERE empusertype=1 and employerid=96

已返回超过1个元素。如果您确定这些记录具有相同的userid字段,请使用IN运算符代替=。也试试这个:

Select distinct userid 
FROM [MyPeople_DataVersion2].[dbo].[EmployerUser] 
WHERE empusertype=1 and employerid=96

它返回唯一的userid,因此你不会得到相同的。

答案 1 :(得分:1)

尝试IN关键字而不是=

Select top 1  name, email, password FROM [MyPeople_DataVersion2].[dbo].[user]
 WHERE id IN (Select userid FROM [MyPeople_DataVersion2].[dbo].[EmployerUser]
 WHERE empusertype=1 and employerid=96)

答案 2 :(得分:1)

SELECT TOP 1
        name
       ,email
       ,password
FROM    MyPeople_DataVersion2.dbo.[user] usr
JOIN    MyPeople_DataVersion2.dbo.EmployerUser empUsr
ON      usr.id = empUsr.userid
WHERE   empUsr.empusertype = 1
        AND empUsr.employerid = 96