一个简单的三表连接查询,在线等

helloMoney 2006-08-30 10:53:32
--一个简单的三表连接查询,表结构如下

--个人表
create table person(
pid int primary key identity(1,1),
personName varchar(20) not null,
)
--物品表
create table things(
tid int primary key identity(1,1),
thingName varchar(20)
)
--关联人和物品
create table myThings(
pid int not null,
tid int not null,
)

insert into person values('tom')
insert into person values('jerry')
insert into person values('jack')

insert into things values('phone')
insert into things values('computer')
insert into things values('camera')

insert into myThings values(1,2)
insert into myThings values(1,3)
insert into myThings values(1,1)

insert into myThings values(2,2)
insert into myThings values(2,3)
insert into myThings values(3,1)

/*
我想要的实现功能如下
如果要显示有phone的人,显示tom和jack
如果要显示有computer,camera的人,则是tom和jerry
如果要显示3种物品都有的人,则只有一个tom

要求只用一条SQL语句搞定以上3种功能
或者设计其他便于这种查询的表结构
*/
...全文
279 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
helloMoney 2006-08-30
  • 打赏
  • 举报
回复
非常感谢!
zsforever 2006-08-30
  • 打赏
  • 举报
回复
注意:如果物品列表有不在物品表(things)里的物品,结果将不考虑这样的物品
tanqimin 2006-08-30
  • 打赏
  • 举报
回复
说真的,楼主要实现这样的交互功能,完全在SQL里面是不能做的,配合其他的开发工具,实用Where语句就能实现,很简单的
specialsoldier 2006-08-30
  • 打赏
  • 举报
回复
3c? haha
zsforever 2006-08-30
  • 打赏
  • 举报
回复
select
distinct p.personName
from
person p,things t,myThings m
where
p.pid=m.pid and t.tid=m.tid
and
not exists(select
1
from
things t1
where
t1.thingName in(...) --替换成物品列表
and
t1.tid not in (select
tid
from
myThings
where
pid=m.pid
)
)
Jane_64 2006-08-30
  • 打赏
  • 举报
回复
declare @things varchar(2000)
set @things='phone'

select personName
from person
where pid in (select pid from myThings where tid in (select tid
from things
where charindex(thingName,@things)>0))
子陌红尘 2006-08-30
  • 打赏
  • 举报
回复
try:

select
distinct p.personName
from
person p,things t,myThings m
where
p.pid=m.pid and t.id=m.tid
and
not exists(select
1
from
things t1
where
t1.tid in(...) --替换成物品列表
and
not exists(select
1
from
myThings
where
pid=p.pid and tid in(...)
)
)

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧