MSSQL中的等效SQL查询

时间:2013-11-21 09:49:02

标签: mysql sql sql-server

以下查询在MySQL中成功执行但在MSSQL中抛出错误。任何人都可以在MSSQL 2008中为我提供等效查询的示例吗?

SELECT DISTINCT TOP 20 
  [users].[id], [users].[email], [users].[first_name], [users].[last_name], 
  (SELECT groups_groups.name 
   FROM users AS groups_users 
     LEFT JOIN users_groups AS groups_users_groups ON groups_users_groups.user_id = groups_users.id 
     LEFT JOIN groups AS groups_groups ON groups_groups.id = groups_users_groups.group_id 
   WHERE users.id = groups_users_groups.user_id) AS [groups] 
FROM [users] GROUP BY [users].[id], [users].[email], [users].[first_name], [users].[last_name] 
ORDER BY [users].[id] DESC

错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression

4 个答案:

答案 0 :(得分:1)

SQL Server返回该错误,因为您的子查询返回多个值,并且无法在单个记录中为用户分配多个值。

我认为你可以做到以下几点:

  1. 检查子查询的逻辑,以便每个用户只返回一条记录。
  2. 修复数据,以便子查询只返回一条记录。

答案 1 :(得分:0)

也许你的问题可能是子查询返回了多个结果..试试

SELECT DISTINCT TOP 20 
  [users].[id], [users].[email], [users].[first_name], [users].[last_name], 
  (SELECT TOP 1 groups_groups.name 
   FROM users AS groups_users 
     LEFT JOIN users_groups AS groups_users_groups ON groups_users_groups.user_id = groups_users.id 
     LEFT JOIN groups AS groups_groups ON groups_groups.id = groups_users_groups.group_id 
   WHERE users.id = groups_users_groups.user_id) AS [groups] 
FROM [users] GROUP BY [users].[id], [users].[email], [users].[first_name], [users].[last_name] 
ORDER BY [users].[id] DESC

答案 2 :(得分:0)

顺便说一句,在MySQL中,该子查询可以简化为......

SELECT DISTINCT g.name FROM groups_groups g

答案 3 :(得分:0)

   SELECT users.id as id ,groups_groups.name  into #groups
   FROM users AS groups_users 
   LEFT JOIN users_groups AS groups_users_groups 
       ON groups_users_groups.user_id = groups_users.id 
   LEFT JOIN groups AS groups_groups 
        ON groups_groups.id = groups_users_groups.group_id 
   WHERE users.id = groups_users_groups.user_id

  SELECT DISTINCT TOP 20 
  [users].[id], [users].[email], [users].[first_name], [users].[last_name], g.name
  FROM [users] 
  inner join #groups g  on users.id=g.id 
  ORDER BY [users].[id] DESC

这不是一个经过测试的代码片段,但是从查询中提到的查询看起来像是,如果目标是获取该组用户数据的所有组(复制用户数据但是新的组名)并且将错误抛出为单个字段的子查询返回多个值....如果上面的情况是这样的话 基于连接所需的表将所有user.id和groups.name放入临时表,然后执行内部联接以将所有用户数据与基于id的组名组合,以获取所需的数据