如何在SQLite子查询连接中指定列

时间:2013-06-29 20:42:57

标签: sql sqlite

我有以下SQL Server查询,我想将其移植到SQLite 3,但它不喜欢它并抱怨语法错误“near(”。

经过一些调试后,问题似乎是SQLite不喜欢子查询别名之后的列说明符(我用双星号表示了这些)。

我需要做什么才能使此查询与SQLite一起使用?

    SELECT  rowSet.DBId_0,
        rowSet.TableID_0, 
        CASE WHEN rowSet.HasIdentity_0 != rowSet.HasIdentity_1 THEN 1 ELSE 0 END 'Result'
FROM (
    SELECT * 
    FROM
    (
        SELECT 'Master' AS 'Db', z.[DBId], z.[TableId], MAX(z.[MaxIdentity]) AS 'HasIdentity' 
        FROM
        (
            SELECT so.[DBId], sc.[TableId], MAX(CAST(sc.[Identity] AS TINYINT)) AS MaxIdentity
            FROM syscolumns sc
                JOIN sysobjects so ON sc.[tableid] = so.[id]
            WHERE so.[dbid] = 1
            GROUP BY so.[DBId], sc.[TableId], sc.[Identity]
        ) z
        GROUP BY z.[DBId], z.TableId
    ) **src (Db_0, DBId_0, TableID_0, HasIdentity_0)**
    JOIN 
    (
        SELECT 'Target' AS 'Db', z.[DBId], z.[TableId], MAX(z.[MaxIdentity]) AS 'HasIdentity' 
        FROM
        (
            SELECT so.[DBId], sc.[TableId], MAX(CAST(sc.[Identity] AS TINYINT)) AS MaxIdentity
            FROM target.syscolumns sc
                JOIN target.sysobjects so ON sc.[tableid] = so.[id]
            WHERE so.[dbid] = 1
            GROUP BY so.[DBId], sc.[TableId], sc.[Identity]
        ) z
        GROUP BY z.[DBId], z.TableId
    ) **tar (Db_1, DBId_1, TableID_1, HasIdentity_1)** ON tar.[DBId_1] = src.[DBId_0] AND tar.[TableId_1] = src.[TableId_0]
) rowSet

以下是您可以尝试的示例查询:

这适用于(在SQLite中):

select col1, col2
from
(
    select 1 as 'col1', 2 as 'col2'
    union
    select 3 as 'col1', 4 as 'col2'
)

这不是(在SQLite中):

select col1, col2
from
(
    select 1 as 'col1', 2 as 'col2'
    union
    select 3 as 'col1', 4 as 'col2'
) z (col1, col2)

2 个答案:

答案 0 :(得分:2)

重命名列的标准SQL方法是使用列别名,即:

SELECT z.col1, z.col2
FROM
(
    SELECT 1 AS col1, 2 AS col2
    UNION ALL
    SELECT 3,         4
) AS z

答案 1 :(得分:1)

您可以对子查询中的列进行别名,但在表别名中,您无法再次指定别名。在以下查询中,您可以在子查询外指定表别名,并在其中指定列别名:

select col1, something
from
(
    select 1 as 'col1', 2 as 'something'
    union
    select 3, 4 
) z