加入子查询而不使用USING

时间:2013-10-10 11:47:53

标签: sql sql-server tsql

我有这样的查询

SELECT DISTINCT
    [fldID],
    [fldValue]
            FROM
                (
                    (
                        SELECT
                            alias1.[fldID],
                            alias1.[fldValue]
                        FROM someT as alias1
                            ....
                    )
                ) AS subQuery_1
            INNER JOIN
            (
                SELECT
                    alias1.[fldID],
                    alias1.[fldValue]
                FROM someT as alias1
                    ...
            ) AS subQuery_2 USING( fldID, fldValue) 

它在MySQL中工作正常,但SQL Server不支持USING。所以我必须像这样使用JOIN:

ON [subQuery_1].[fldID] = [subQuery_2].[fldID] 
AND [subQuery_1].[fldValue] = [subQuery_2].[fldValue]

但是这个查询会导致错误:

Ambiguous column name fldID 
Ambiguous column name fldValue

那么,我如何在SQL Server中实现这种JOIN?

2 个答案:

答案 0 :(得分:2)

您只需要指定从哪个子查询中获取这些列(当您在两个列上加入时,在您的案例中使用哪个子集无关紧要)

SELECT DISTINCT
subQuery_1.[fldID],
subQuery_1.[fldValue]
        FROM
            (
                (
                    SELECT
                        alias1.[fldID],
                        alias1.[fldValue]
                    FROM someT as alias1
                        ....
                )
            ) AS subQuery_1
        INNER JOIN
        (
            SELECT
                alias1.[fldID],
                alias1.[fldValue]
            FROM someT as alias1
                ...
        ) AS subQuery_2 
 ON [subQuery_1].[fldID] = [subQuery_2].[fldID] 
 AND [subQuery_1].[fldValue] = [subQuery_2].[fldValue]

答案 1 :(得分:0)

在查询中,您不是在最终选择中添加表别名。您需要指定来自哪个表的列,如下所示:

SELECT DISTINCT
    subQuery_1.[fldID],
    subQuery_1.[fldValue]
            FROM
                (
                    (
                        SELECT
                            alias1.[fldID],
                            alias1.[fldValue]
                        FROM someT as alias1
                            ....
                    )
                ) AS subQuery_1
            INNER JOIN
            (
                SELECT
                    alias1.[fldID],
                    alias1.[fldValue]
                FROM someT as alias1
                    ...
            ) AS subQuery_2 
            on [subQuery_1].[fldID] = [subQuery_2].[fldID] 
AND [subQuery_1].[fldValue] = [subQuery_2].[fldValue]