连接查询中不等式的运用

假设有这样一个实例:
create table a(dept_id int, user_id int)
insert into a select 1, 1
insert into a select 1, 2
insert into a select 1, 13
insert into a select 1, 4

insert into a select 2, 4
insert into a select 2, 1
insert into a select 2, 13

insert into a select 3, 1
insert into a select 3, 10
insert into a select 3, 4

select * from a

表a记录着dept和user的关系,2个dept中只要有2个以上的相同user,那么我们就认为这2个dept有关联,把这样的dept找出来,返回:

dept_id dept_id
1 2
1 3
2 3

(注意只保留一种对应情况,剔除掉重复情况)

实际案例:
通过人员比较来确定单位是否相同
其中只要有三个以上相同的人员,我们就认为是同一个单位了

[@more@]

SQL如下,注意这里使用"
select x.dept_id as aa, y.dept_id as bb
from a x, a y
where x.user_id = y.user_id and x.dept_id < y.dept_id
group by x.dept_id, y.dept_id
having count(*) >= 2
order by aa

可以和以下SQL比较:
select x.dept_id as aa, y.dept_id as bb
from a x, a y
where x.user_id = y.user_id and x.dept_id <> y.dept_id
group by x.dept_id, y.dept_id
having count(*) >= 2
order by aa

第一条SQL只取x中dept_id小于y中dept_id的记录,过滤了重复记录!很巧妙。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/66009/viewspace-881832/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/66009/viewspace-881832/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值