有这么一个表,存储着两个对象;
id key value
1 a 11
1 b 22
1 c 33
2 a 11
2 c 33
2 d 44我想查询出某几个属性值与对象1相同的对象的个数。这里的对象1 (a=11,b=22,c=33),对象2(a=11,c=33,d=44),如果属性为a,c的话,结果显然应该是1。Sql怎么写?下面是我错误的代码:
select count(b.id)
from table a, table b
where a.key=b.key
and a.value=b.value
and b.id<>1
and a.key in (select key from table where another_rule); -- 相当于in('a','c')这里select key from table where another_rule就是为了查询出a,c,这两个属性也是动态的。
这个代码肯定错了,它的结果会是2,我知道错误原因,现在求正确的sql。
id key value
1 a 11
1 b 22
1 c 33
2 a 11
2 c 33
2 d 44我想查询出某几个属性值与对象1相同的对象的个数。这里的对象1 (a=11,b=22,c=33),对象2(a=11,c=33,d=44),如果属性为a,c的话,结果显然应该是1。Sql怎么写?下面是我错误的代码:
select count(b.id)
from table a, table b
where a.key=b.key
and a.value=b.value
and b.id<>1
and a.key in (select key from table where another_rule); -- 相当于in('a','c')这里select key from table where another_rule就是为了查询出a,c,这两个属性也是动态的。
这个代码肯定错了,它的结果会是2,我知道错误原因,现在求正确的sql。
解决方案 »
- 关于流复制技术-表空间级复制
- 寻求一个SQL查询语句
- 请教一个关与公交换乘的SQL或者过程
- sqlloader(不符合条件的数据不导入到数据库中),如何实现?
- oracle中各基本数据类型分别代表什么?有没有整型数?
- 两台机器上装有不同ORACLE版本,相互间无法连接
- 急!急!急!各位大虾!请问在Oracle中如何定义外键组??
- ORA-01589:这个错误的形成原因是什么?
- hibernate query.list() 方法为什会卡死
- plsql 显示登录成功,但是执行语句时报 ORA-03114: 未连接到ORACLE
- 如何写函数?????????????
- 查询语句的怪问题,大家帮忙解释一下
--AND A.KEY = 'A'
--AND A.KEY = 'C'
不知是不是这样
To duanzilin: 不可以,上面的sql错误在于select key from table where another_rule,必须保证这个结果集中的n个属性的值同时相等,这个句法的实际意思却是结果集中的n个属性的值中任意一个相等即可。To sduzjw:您看出问题了,但是这个A,C都是查出来得,sql写的时候,不知道查询结果,所以AND A.KEY = 'A'...不可能写的
select distinct t1.id,t1.key from a t1
where exists(select * from a where key in('a','c') and id=1 and key=t1.key)) group by id having count(id)>1
select distinct t1.id,t1.key from a t1
where exists(select * from a where key in('a','c') and id=1 and key=t1.key))
group by id having count(id)=(select count(*) from (select distinct id,key from a where key in('a','c') and id=1))
where not exists (
select * from a t2 where t2.id=1 and t2.key in('a','c') and not exists(
select * from a t3 where
t3.id=t1.id and t3.key=t2.key and t2.key<>t1.key))