交叉连接Sql查询

时间:2012-03-02 18:05:56

标签: sql-server-2008

    CREATE TABLE [dbo].[Country](
        [Id] [int] NOT NULL,
        [name] [varchar](50) NULL)

    CREATE TABLE [dbo].[State](
        [Id] [int] NOT NULL,
        [name] [varchar](50) NULL,
             [CountryId] [int] NULL references Country(Id))

    CREATE TABLE [dbo].[City](
        [Id] [int] NOT NULL,
        [name] [varchar](50) NULL,
             [StateId] [int] NULL references State(Id))

Value in table 

国家

-------
1 USA
2 UK

国家

-----
1 NY 1
2 NSW NULL

-----
1 Sydney 2
2 Mumbai NULL
3 Delhi 1

现在我想要City.Name,State.Name,Country.Name列表也是NULL值。

例如悉尼新南威尔士州      德里纽约美国 避免重复记录

我尝试了这个查询,但其中有一些错误:

SELECT        Country.name, City.Name AS Expr1, State.Name AS Expr2
FROM            City CROSS JOIN
                         State CROSS JOIN
                         Country
WHERE        (City.StateId IN
                             (SELECT        StateId
                               FROM            City AS City_1)) OR
                         (State.CountryId IN
                             (SELECT        CountryId
                               FROM            State AS State_1))

1 个答案:

答案 0 :(得分:2)

SELECT        C2.name, C.Name AS Expr1, S.Name AS Expr2
FROM            City c 
LEFT OUTER  JOIN State s ON c.stateid = s.id
LEFT OUTER  JOIN Country c2 on s.countryId = c2.id