如何避免笛卡尔连接

sinxy 2008-02-21 02:39:16
有一条SQL语句
select aa.col1,aa.col2,aa.col3, ... ,bb.col1,bb.col2 from table1 aa,table2 bb
where aa.ID = bb.ID


现在的逻辑是要取出和它条件相反的纪录,即table1.ID 不等于 table2.ID 的纪录
我写的SQL是
select aa.col1,aa.col2,aa.col3, ... ,bb.col1,bb.col2 from table1 aa,table2 bb
where aa.ID not in (Select ID from table2)


但是这样取的话,就出现了笛卡尔积,虽然取出了纪录,但是纪录总数目是正确情况的count倍(count为table2的纪录数)

请问该怎样写这条SQL,避免笛卡尔积。
...全文
383 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
lainY7mail 2008-02-21
  • 打赏
  • 举报
回复
1楼正解
viva369 2008-02-21
  • 打赏
  • 举报
回复
table1.ID 不等于 table2.ID
那你怎么取出table2列的值,是你写错了,还是我理解错了
viva369 2008-02-21
  • 打赏
  • 举报
回复
你这个是交叉连接。

wangdehao 2008-02-21
  • 打赏
  • 举报
回复
select a.*
from table1 a
left join table2 b
on a.id=b.id
where b.id is null
wangdehao 2008-02-21
  • 打赏
  • 举报
回复
select *
from table1
where id not in(Select ID from table2)

---笛卡尔积是你自己写进去的
wangdehao 2008-02-21
  • 打赏
  • 举报
回复
select * from table1 a
where not exists(
select * from table2 where id = a.id
)
zefuzhang2008 2008-02-21
  • 打赏
  • 举报
回复
select aa.col1,aa.col2,aa.col3, ... ,bb.col1,bb.col2 from table1 aa left join table2 bb
on aa.id=bb.id
where bb.id is null
union
select aa.col1,aa.col2,aa.col3, ... ,bb.col1,bb.col2 from table1 aa right join table2 bb
on aa.id=bb.id
where aa.id is null



JiangHongTao 2008-02-21
  • 打赏
  • 举报
回复
直接写不好吗
--table1有table2没有的
select * from table1 where ID not in (Select ID from table2)
--table2有table1没有的
select * from table2 where ID not in (Select ID from table1)
--什么,两个都要,对表字段不明,只能取ID
select id,'table2没有' from table1 where ID not in (Select ID from table2)
union
select id,'table1没有' from table2 where ID not in (Select ID from table1)
sinxy 2008-02-21
  • 打赏
  • 举报
回复
发生笛卡尔积的原因在于 select 列表中包含了 table2.ID ,而要选取的table2的ID本身是不存在的,所以把table2.ID从select列表中删去就可以了
sinxy 2008-02-21
  • 打赏
  • 举报
回复
在数据表 table2 中的 ID是 not bull的
所以上面的应该不行 呵呵
pt1314917 2008-02-21
  • 打赏
  • 举报
回复

--try:

select aa.col1,aa.col2,aa.col3, ... ,bb.col1,bb.col2 from table1 aa left join table2 bb
on aa.id=bb.id and bb.id is null


34,838

社区成员

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

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