首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

这样的SQL语句如何写

2012-02-16 
这样的SQL语句怎么写有三个表如下p表pidpname1书2报3衣服4裤子o表oidpiduid111212321431u表uiduname1张2王

这样的SQL语句怎么写
有三个表   如下
p   表
pid         pname        
1             书              
2             报              
3             衣服          
4             裤子          

o   表
oid           pid           uid
1                 1               1
2                 1               2
3                 2               1
4                 3               1

u   表
uid           uname
1               张
2               王

求sql语句完成如下功能

现在uid   1   登陆   看到这样的信息

pid       pname         isorder
1             书               true
2             报               true
3             衣服           true
4             裤子           false

如果   uid   2   登陆   看到这样的信息

pid       pname         isorder
1             书               true
2             报               false
3             衣服           false
4             裤子           false

[解决办法]

create table P(pid int, pname varchar(10))
insert P select 1, '书 '
union all select 2, '报 '
union all select 3, '衣服 '
union all select 4, '裤子 '
go
create table O(oid int, pid int, uid int)
insert O select 1, 1, 1
union all select 2, 1, 2
union all select 3, 2, 1
union all select 4, 3, 1
go
create table U(uid int, uname varchar(10))
insert U select 1, '张 '
union all select 2, '王 '

--用戶1
select *,
isorder=case when exists(select 1 from O where pid=tmp.pid and uid=1) then 'true ' else 'false ' end
from P tmp
--result
pid pname isorder
----------- ---------- -------
1 书 true
2 报 true
3 衣服 true
4 裤子 false

(4 row(s) affected)

--用戶2
select *,
isorder=case when exists(select 1 from O where pid=tmp.pid and uid=2) then 'true ' else 'false ' end
from P tmp
--result
pid pname isorder
----------- ---------- -------


1 书 true
2 报 false
3 衣服 false
4 裤子 false

(4 row(s) affected)

热点排行