有一個表A,有二個字段a和b,結構及數據如下:Aa        b
------------
我       我和你都是小學生
你       你是學生問題:
我想第一先查a like '%你%' 然後接上 b like '%你%'
正確排序是:
a        b
------------
你       你是學生
我       我和你都是小學生但是如果我用下面的語句便出錯了。
select * from a where a like '%你%'
UNION
select * from a where b like '%你%'先排查詢a字段的資料,再排查詢b字段的。這語句怎么寫?

解决方案 »

  1.   

    select a,b
    from 
        (
            select a,b,1 as xh from a where a like '%你%'
            UNION
            select a,b,2 as xh from a where b like '%你%'
        ) AS T
    order by xh
      

  2.   

    --创建测试环境
    create table a(a varchar(100),b varchar(100))
    --追加测试数据
    insert into a select '你',       '你是學生'
    insert into a select '我',       '我和你都是小學生'
    --查询SQL
    select a,b
    from 
        (
            select a,b,1 as xh from a where a like '%你%'
            UNION
            select a,b,2 as xh from a where b like '%你%'
        ) AS T
    group by a,b
    order by min(xh)
    --删除测试表
    drop table A
      

  3.   

    直接order by不行吗?
    select * from a order by a asc
      

  4.   

    --或
    select *
    from A
    order by case when a like '%你%' then 1 when b like '%你%' then 2 end
      

  5.   

    --创建测试环境
    create table a(a varchar(100),b varchar(100))
    --追加测试数据
    insert into a select '你',       '你是學生'
    insert into a select '我',       '我和你都是小學生'
    --查询SQL
    select a,b
    from 
        (
            select a,b,1 as xh from a where a like '%你%'
            UNION
            select a,b,2 as xh from a where b like '%你%'
        ) AS T
    group by a,b
    order by min(xh)
    --或select *
    from A
    order by case when a like '%你%' then 1 when b like '%你%' then 2 end
    --删除测试表
    drop table A