这样的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)