求一句SQL语句,能不能不用JOIN

roundman 2007-08-31 09:37:48
现有一数据表
项目ID KEY VALUE
项目1 1 5
项目1 2 3
项目1 3 2
项目2 1 4
项目2 2 1
项目2 3 7
项目3 1 3
项目3 2 4
项目3 3 6

要求:
KEY=1,VALUE<=5;
KEY=2,VALUE<=3;
KEY=3,VALUE<=5;
取出满足以上3个条件的项目(当然,KEY对应的VALUE值可以变化)

理论上结果应该是项目1

我能想到的就是把自己这张表JOIN N次,每次应用不同的KEY和VALUE值.
各位看看能不能不用JOIN就把需要的记录取出来,因为实际的KEY值数量可能是变化的,而表中数据量又不小...一旦JOIN太多影响效率的吧....
...全文
151 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
roundman 2007-08-31
  • 打赏
  • 举报
回复
恩,了解,那就这么做吧...
dawugui 2007-08-31
  • 打赏
  • 举报
回复
如果每种情况都有多个话,要么左连接,要么内连接.
roundman 2007-08-31
  • 打赏
  • 举报
回复
TO dawugui(潇洒老乌龟)
这个方法和JOIN差不多,都是有几个条件就叉乘几遍表吧?
总感觉数据量大的情况下(比如每个条件符合的记录有M条,而条件有N个,那是不是FROM的结果集有M^N条记录?
很慌啊....数据库的负担会很严重的吧...

playwarcraft 2007-08-31
  • 打赏
  • 举报
回复
應該是都滿足?
select * from tb t where KEY=1 and VALUE<=5
and exists(select 1 from tb where KEY=2 and VALUE<=3 and 項目=t.項目)
and exists(select 1 from tb where KEY=3 and VALUE<=5 and 項目=t.項目)
dawugui 2007-08-31
  • 打赏
  • 举报
回复
--不好意思,上面两个错了.

create table tb(项目ID varchar(10),[KEY] int,VALUE int)
insert into tb values('项目1', 1, 5)
insert into tb values('项目1', 2, 3)
insert into tb values('项目1', 3, 2)
insert into tb values('项目2', 1, 4)
insert into tb values('项目2', 2, 1)
insert into tb values('项目2', 3, 7)
insert into tb values('项目3', 1, 3)
insert into tb values('项目3', 2, 4)
insert into tb values('项目3', 3, 6)

select t1.项目ID from
(select * from tb where [KEY]=1 and VALUE<=5) t1,
(select * from tb where [KEY]=2 and VALUE<=3) t2,
(select * from tb where [KEY]=3 and VALUE<=5) t3
where t1.项目ID = t2.项目ID and t1.项目ID = t3.项目ID

drop table tb

/*
项目ID
----------
项目1

(所影响的行数为 1 行)

*/
dawugui 2007-08-31
  • 打赏
  • 举报
回复
select * from tb where (KEY=1 and VALUE<=5) or (KEY=2 and VALUE<=3) or (KEY=3 and VALUE<=5)
dawugui 2007-08-31
  • 打赏
  • 举报
回复
select * from tb where KEY=1 and VALUE<=5
union all
select * from tb where KEY=2 and VALUE<=3
union all
select * from tb where KEY=3 and VALUE<=5

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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