题目:  有一张数据表,暂且就叫location ,包含一个字段location,里面的数据类似这样
        localtion 
        hubei,wuhan
       湖北,武汉
        天津,天津
         
        用一条sql语句是原表结构和数据变成
        province      city
       hubei         wuhan
       湖北            武汉
        天津            天津
       
面试题目,要求用一条sql, 用多条SQL实现也可以讨论开始。。

解决方案 »

  1.   

    create table localtion(
    localtion varchar(20)
    )
    insert into localtion(localtion)
    select 'hubei,wuhan' union all 
    select '湖北,武汉' union all
    select '天津,天津'select SUBSTRING(localtion,1,LOCATE(',',localtion)-1) as province,SUBSTRING(localtion,LOCATE(',',localtion)+1) as city from localtion--Result
    hubei,wuhan
    湖北,武汉
    天津,天津
      

  2.   

    楼上的头像我看起来有些象那个大力水手里面的一个人的头像,呵呵, 
    恩,确实,但是为什么mysql不能象mssql一样用select into 把你这个查询结果导入到一个新的表里面?
      

  3.   

    有个问题,location这个字段以外还有其他字段,我要把其他字段也一起显示出来,例如下面(借楼主的sql一用)
    select SUBSTRING(localtion,1,LOCATE(',',localtion)-1) as province,SUBSTRING(localtion,LOCATE(',',localtion)+1) as city,id as a from localtion  
    前面的province就显示不出来了, 请教下原理。如果我有很多字段都要显示出来,SQL如何写呢?
    求教?
      

  4.   

    把select出来的字符串进行切割,然后插入到表里去
      

  5.   

    分考什么,正常的做一个分割函数。用 select col1,col2 ... f_substr(col1) as expr1 , f_substr(col1) as expr2  from tb 
    的形式。
    要不然就是考你基本字符串处理函数,用上面的方法就成。一句完成。
      

  6.   

    另外。mysql 没有sqlserver表里面所谓的表变量,只能用临时表方法
      

  7.   

    declare @l table(f1 varchar(20))
    insert into @lselect'hubei,wuhan'union all
    select  '湖北,武汉'union all
    select '天津,天津'
     
    select  left(f1,patindex('%[啊-座]%',f1)-1)as' province' ,
            stuff(f1,1,patindex('%[啊-座]%',f1)-1,'')as'city'
    from @l
       
      

  8.   

    数据库:ms sql server
    if exists(select 1 from sysobjects where id = object_id('test'))
    drop table test
    go
    create table test(
        id int identity(1,1) primary key not null,
        location varchar(50) not null
    );
    insert into test values('重庆,重庆');
    insert into test values('四川的,成都');
    insert into test values('重庆,重庆达到');
    insert into test values('云南,昆明');
    insert into test values('重庆,重庆');
    select substring(location,1,patindex('%,%',location)-1) as province,
      substring(location,patindex('%,%',location)+1,len(location)) as city,id from test