请提供简单的SQL Server语法帮助

问题描述 投票:0回答:2

我用这个把我的头撞在墙上。为什么SSMS中的查询编辑器在此查询末尾给我一个关于右括号的错误?

SELECT 
    c.TABLE_NAME,
    c.COLUMN_NAME
FROM 
    INFORMATION_SCHEMA.COLUMNS c
INNER JOIN 
    (SELECT COLUMN_NAME
     FROM INFORMATION_SCHEMA.COLUMNS
     GROUP BY COLUMN_NAME
     HAVING COUNT(*) = 1)

我收到此错误:

['附近的语法不正确]

sql join select syntax-error ssms
2个回答
3
投票

您在括号中缺少子查询的别名和on子句:

SELECT 
    c.TABLE_NAME,
    c.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS c
INNER JOIN 
    (SELECT 
        COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    GROUP BY COLUMN_NAME
    HAVING COUNT(*) = 1
    ) x -- Alias added here
    ON x.COLUMN_NAME = c.COLUMN_NAME -- ON caluse

0
投票

您无需在此处使用join,您可以使用exists

select c.*
from information_schema.columns c
where not exists (select 1 
                  from information_schema.columns c1
                  where (c1.column_name = c.column_name) and
                        (c1.table_name <> c.table_name or c1.table_schema <> c.table_schema)
                );
© www.soinside.com 2019 - 2024. All rights reserved.