日期:2014-05-18  浏览次数:20393 次

一个SQL语句的问题_f
我有两个表

用户表         uid         name
                      1         张三
                      2         李四
                      3         赵五

消息表         mid       sortid     msg
                      1           0           欢迎注册
                      2           0           网站公告
                      3           1           你是张三吗?

用户表就是用户表,消息表就像是网站公告一样,如果sortid=0,则表示针对所有用户发表公告,非0则是针对用户的id

我现在是想得到这样的查询结果
             
mid                 msg               sort
1                 欢迎注册         所有人
2                 网站公告         所有人
3             你是张三吗           张三

我不会弄了,请大家帮帮我,谢谢~~

------解决方案--------------------
select a.mid,a.msg,case when isnull(a.sortid,0)=0 then '所有人 ' else b.name end as sort
from 消息表 a
left join 用户表 b on a.sortid=b.uid
------解决方案--------------------
create table 用户表(uid int,name varchar(10))
insert into 用户表
select 1, '张三 '
union all select 2, '李四 '
union all select 3, '赵五 '

create table 消息表(mid int,sortid int,msg varchar(255))
insert into 消息表
select 1,0, '欢迎注册 '
union all select 2,0, '网站公告 '
union all select 3,1, '你是张三吗? '

select a.mid,a.msg,case when isnull(a.sortid,0)=0 then '所有人 ' else b.name end as sort
from 消息表 a
left join 用户表 b on a.sortid=b.uid
/*
mid msg sort
----------- ------------------- ----------
1 欢迎注册 所有人
2 网站公告 所有人
3 你是张三吗? 张三

(所影响的行数为 3 行)
*/