有两个表 一个地区 一个城市 
地区表里存的是 华北 华南...
城市表里存的是 天津 北京...城市表里存有地区id现在想通过sql语句查询出这样的数据效果名称
------------
华北
天津
北京
...
华南
江苏
浙江
...
华东
沈阳
黑龙江
...

解决方案 »

  1.   

    地区表 ts_dict_dq 字段 id dq 
    数据内容
    1 华北
    2 华东
    3 华南
    5 东北
    6 西南
    7 西北
    8 港澳台
    9 华中 城市表 ts_dict_city 字段 id city dqid1 唐山    1
    2 天津    1
    3 胜芳    1
    4 衡水    1
    5 廊坊    1
    6 北京    1
    7 大厂    1
    8 邯郸    1
      

  2.   

    通过id号将两个表关联,select  id和城市,并通过group by  id  将城市按id分组。
    就ok了。
      

  3.   

    --> 测试数据:[area]
    if object_id('[area]') is not null drop table [area]
    go
    create table [area]([id] int,[name] varchar(4))
    go
    insert [area]
    select 1,'华北' union all
    select 2,'华南' union all
    select 3,'华东'
    --> 测试数据:[city]
    if object_id('[city]') is not null drop table [city]
    go
    create table [city]([id] int,[name] varchar(6),dqid int)
    go
    insert [city]
    select 1,'天津',1 union all
    select 2,'北京',1 union all
    select 3,'江苏',2 union all
    select 4,'浙江',2 union all
    select 5,'沈阳',3 union all
    select 6,'黑龙江',3select name
    from
    (
    select id,name from [area]
    union all
    select dqid,name from [city]
    union all
    select number,'...' 
    from master..spt_values
    where type = 'P' and number between 1 and (select count(1) from [area])
    ) t
    order by id,case when exists (select 1 from [area] where name = t.name) then 1 else 
    (case when  exists (select 1 from [city] where name = t.name) then 2 else 3 end) end
    --------------------------------name
    ------
    华北
    天津
    北京
    ...
    华南
    江苏
    浙江
    ...
    华东
    沈阳
    黑龙江
    ...(12 行受影响)
      

  4.   

    select 城市名称 as 名字 from
    (select * from 
        (select a.地区编码, a.地区名称, '1' as IsCity, b.城市编码, b.城市名称 
        from 地区表 a, 城市表 b where b.地区编码=a.地区编码
        union all
        select c.地区编码, c.地区名称, '0' as IsCity, null as 城市编码, c.地区名称 as 城市名称
        from 地区表 c where exists(select 1 from 城市表 d where d.地区编码=c.地区编码)
       ) order by 地区编码, IsCity, 城市名称
    )
      

  5.   

    --> 测试数据:[area]
    if object_id('[area]') is not null drop table [area]
    go
    create table [area]([id] int,[name] varchar(4))
    go
    insert [area]
    select 1,'华北' union all
    select 2,'华南' union all
    select 3,'华东'
    --> 测试数据:[city]
    if object_id('[city]') is not null drop table [city]
    go
    create table [city]([id] int,[name] varchar(6),dqid int)
    go
    insert [city]
    select 1,'天津',1 union all
    select 2,'北京',1 union all
    select 3,'江苏',2 union all
    select 4,'浙江',2 union all
    select 5,'沈阳',3 union all
    select 6,'黑龙江',3select name
    from
    (
    select id,name,px=id,px1=0 from [area]
    union all
    select dqid,name,px=dqid,px1=1 from [city] 
    ) t
    order by px,px1,id
    /*
    name
    ------
    华北
    天津
    北京
    华南
    江苏
    浙江
    华东
    沈阳
    黑龙江(9 行受影响)
    */5L的测试数据