2

使用 SQL Server 2008

目标:从table1中选择一系列列插入到table2中

问题:在 table2 中,需要插入一个额外的列,可以从 table1 和 table 3 之间的连接派生

当前代码

SELECT
    table1.name,
    table1.email,
    table1.phone,
    CASE WHEN table1.status = 'active' THEN 1 ELSE 0 END AS Active,
    CASE WHEN table1.group_id = 3 THEN 5 ELSE table1.group_id END AS RoleId,
    (SELECT
        table3.UserID AS ParentID
     FROM
         table3
     INNER JOIN
         table1 ON
         table3.ID = table1.table3_ID)
FROM
    table1
WHERE
    table1.group_id = 3 AND
    table1.status = 'active'

目前此代码不起作用并返回“子查询返回超过 1 个值”错误。我知道这可能不是使用嵌套选择的正确方法,正确的方法是什么?

如有必要,可提供额外数据。先感谢您。

4

3 回答 3

1

问题是你想要一个相关的子查询。这意味着您需要table1从子查询中删除:

SELECT table1.name, table1.email, table1.phone,
       (CASE WHEN table1.status = 'active' THEN 1 ELSE 0 END) AS Active,
       (CASE WHEN table1.group_id = 3 THEN 5 ELSE table1.group_id END) AS RoleId,
       (SELECT table3.UserID 
        FROM table3
        WHERE table3.ID = table1.table3_ID
       ) as ParentID
FROM table1
WHERE table1.group_id = 3 AND table1.status = 'active';

如果 中有多个可能的匹配项table3,那么您将需要类似select top 1 table3.UserIdor的内容select max(table3.UserId)

于 2013-09-12T18:34:43.987 回答
1

如果你真的(真的真的真的)想要使用subquery而不是join你的代码就很好了。您应该如下更改您的子查询join

SELECT
    table1.name,
    table1.email,
    table1.phone,
    CASE WHEN table1.status = 'active' THEN 1 ELSE 0 END AS Active,
    CASE WHEN table1.group_id = 3 THEN 5 ELSE table1.group_id END AS RoleId,
    (SELECT
        table3.UserID 
     FROM
         table3
     WHERE
         table3.ID = table1.table3_ID) AS ParentID
FROM
    table1
WHERE
    table1.group_id = 3 AND
    table1.status = 'active'

除此之外,我ParentIDsubquery.


请考虑以下带有表别名的代码。使用它是一个好习惯,因为代码更具可读性。

SELECT
    t1.name,
    t1.email,
    t1.phone,
    CASE WHEN t1.status = 'active' THEN 1 ELSE 0 END AS Active,
    CASE WHEN t1.group_id = 3 THEN 5 ELSE t1.group_id END AS RoleId,
    (SELECT
        table3.UserID 
     FROM
         table3 t3
     WHERE
         t3.ID = t1.table3_ID) AS ParentID
FROM
    table1 t1
WHERE
    t1.group_id = 3 AND
    t1.status = 'active'
于 2013-09-12T18:28:14.783 回答
1

您可以通过将 TOP 1 添加到选择的“select .. from table”部分来解决多于 1 个值的错误。但只是内部加入它们可能更容易。

SELECT
table1.name,
table1.email,
table1.phone,
CASE WHEN table1.status = 'active' THEN 1 ELSE 0 END AS Active,
CASE WHEN table1.group_id = 3 THEN 5 ELSE table1.group_id END AS RoleId,
table3.UserID
FROM    table1
INNER JOIN table3 ON
     table3.ID = table1.table3_ID
WHERE
table1.group_id = 3 AND
table1.status = 'active'
于 2013-09-12T18:32:50.217 回答