如何在SQL 2008中的主查询中实现子查询引用表内的连接

时间:2011-08-10 04:56:44

标签: sql-server tsql sql-server-2008 join sql-server-2000

我有一个以下查询,它在子查询中加入,而连接表是从主查询from子句引用的。这是SQL Server 2000语法,我试图将其迁移到2008语法,但我在运行时收到错误。请建议。

CREATE TABLE [dbo].[PRODUCT]
(
        [pid] [int] NULL,
        [NAME] [nchar](10) NULL,
        [PDID] [int] NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[PRODUCTDESC]
(
        [PDID] [int] NULL,
        [DESC] [nchar](10) NULL
) ON [PRIMARY]

--Test Data
insert into PRODUCT values (1,'ONE',1);
insert into PRODUCT values (2,'2',2);
insert into PRODUCT values (3,'3',2);
insert into PRODUCT values (4,'4',null);
insert into PRODUCT values (5,'4',5);

INSERT INTO PRODUCTDESC VALUES (1,'ONENEN');
INSERT INTO PRODUCTDESC VALUES (2,'TWEONEN');

-- SQL Server 2000
SELECT 
    Name,
    (SELECT [DESC]
     FROM PRODUCTDESC
     WHERE PRODUCT.PDID *= PRODUCTDESC.PDID)
FROM   
    PRODUCT 

--RESULTS
/*
    Name    (No column name)
    ONE         ONENEN    
    2           TWEONEN   
    3           TWEONEN   
    4           NULL
    */

-- SQL Server 2008
SELECT 
    NAME,
    (SELECT [DESC]
     FROM PRODUCT
     LEFT OUTER JOIN PRODUCTDESC ON PRODUCT.PDID = PRODUCTDESC.PDID)
FROM   
    PRODUCT 

--RESULTS
/*
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
*/

在上面的2008查询中,在子查询中如何访问主查询表单子句中引用的TABLES,这样我就不会得到子查询returend超过1的值错误

请建议。

3 个答案:

答案 0 :(得分:2)

SELECT PRODUCT.NAME
       ,PRODUCTDESC.[DESC]
FROM   PRODUCT
LEFT JOIN PRODUCTDESC
    ON PRODUCT.PDID = PRODUCTDESC.PDID

请注意,问题是因为你有一个标量子查询,它必须只返回一行(或没有行)。请注意,这意味着具有该数据的原始查询也将在SQL Server 2000中失败。此外,在SQL Server 2000和SQL Server 2008R2以及它们之间的所有版本中,甚至不需要左连接* =运算符:

DECLARE @PRODUCT TABLE (
    [PDID] [int] NULL,
    [NAME] [nchar](10) NULL
)

DECLARE @PRODUCTDESC TABLE (
    [PDID] [int] NULL,
    [DESC] [nchar](10) NULL
)

--Test Data
insert into @PRODUCT values (1,'ONE');
insert into @PRODUCT values (2,'2');
insert into @PRODUCT values (3,'3');
insert into @PRODUCT values (4,'4');

INSERT INTO @PRODUCTDESC VALUES (1,'ONENEN');
INSERT INTO @PRODUCTDESC VALUES (2,'TWEONEN');


--SQL 2000-2008R2
SELECT Name,
       (SELECT [DESC]
        FROM   @PRODUCTDESC AS PRODUCTDESC
        WHERE  PRODUCT.PDID = PRODUCTDESC.PDID)
FROM   @PRODUCT AS PRODUCT

答案 1 :(得分:0)

这是你想要做的吗?

select p.Name,pdesc.DESC, from PRODUCT p inner join PRODUCTDESC pdesc on pdesc.PDID=p.PDID

答案 2 :(得分:0)

您的子查询中不需要外部联接。这样可以正常工作。

SELECT Name,
       (SELECT [DESC]
        FROM   PRODUCTDESC
        WHERE  PRODUCT.PDID = PRODUCTDESC.PDID)
FROM   PRODUCT