像这样的表
int char int int
id name a_id b_id
SELECT count(*) FROM tbl t1 WHERE b_id = 12 AND NOT EXISTS(select * from tbl t2 where t2.a_id = t1.b_id AND t2.b_id = t1.a_id)
我认为它至少等于
SELECT count(*) FROM tbl t1 WHERE b_id = 12 AND NOT EXISTS(select * from tbl t2 where t2.a_id = 12 AND t2.b_id = t1.a_id)
那么这是什么意思?
例如,SELECT a_id FROM tbl t1 WHERE b_id = 12
给出1,2,3,4
然后执行以下操作:
select * from tbl t2 where t2.a_id = 12 AND t2.b_id = 1 # NULL
select * from tbl t2 where t2.a_id = 12 AND t2.b_id = 2 # exists
select * from tbl t2 where t2.a_id = 12 AND t2.b_id = 3 # exists
select * from tbl t2 where t2.a_id = 12 AND t2.b_id = 4 # NULL
所以count(*)将是2?
答案 0 :(得分:0)
这个非常有趣,因为它找到了#34;对称性"在a_id和b_id中,数字为12,所以基本上它计算表中的行数,其中b_id = 12除了具有对称对的那些,如下所示:
| a_id | b_id |
---------------
| 12 | 12 |
| 12 | 2 |
| 2 | 12 |
或者更一般地说,查询跳过计算a_id = X b_id = 12的行,并且存在a_id = 12和b_12 = X的另一行。
因此,NOT EXISTS只是跳过计数具有对称对的行,我不知道这在大多数应用程序中有用,但它仍然很有趣。