数据库表test1的数据内容是
t1 d1
--------------
1 1
1 100
100 200 (A)
select * from test1 GROUP by t1 having count(t1)>1;
这条语句只能查询出一个查询结果
(B)
select * from test1 a where exists (select * from test1 where t1=a.t1 GROUP by t1 having count(t1)>1)
而这条语句可以查询出2条结果,不懂其中的原理!对于A 为什么select * 只能显示一条结果,但是select count(1)或 count(*) 可以显示两条结果小弟主要是对exists 不太明白,知道exists其实返回的是true 和false,好像还和where里面的限定条件有关 请高人解答!
t1 d1
--------------
1 1
1 100
100 200 (A)
select * from test1 GROUP by t1 having count(t1)>1;
这条语句只能查询出一个查询结果
(B)
select * from test1 a where exists (select * from test1 where t1=a.t1 GROUP by t1 having count(t1)>1)
而这条语句可以查询出2条结果,不懂其中的原理!对于A 为什么select * 只能显示一条结果,但是select count(1)或 count(*) 可以显示两条结果小弟主要是对exists 不太明白,知道exists其实返回的是true 和false,好像还和where里面的限定条件有关 请高人解答!
group 的结果是+------+------+
| t1 | d1 |
+------+------+
| 1 | 1 |
| 100 | 200 |
+------+------+因为GROUP BY T1,这样当有多条记录时,只随机取了第一条。
然后再做判断 having count(t1)>1 这样只有 1,1 这条记录被选中。
select * from test1 a where exists (select * from test1 where t1=a.t1 GROUP by t1 having count(t1)>1) 这个是对每条记录都检测一下 exists (select * from test1 where t1=a.t1 GROUP by t1 having count(t1)>1) 所以会返回两条记录。
先根据字段t1进行分组,这样的结果就是
t1,d1,total_count
1,1,2
100,200,1
然后再对上面的结果进行having count(t1)>1,则只有第一行的结果符合,所以最终结果为:
t1,d1,total_count
1,1,2
即对test1 a里面的每条记录进行扫描,扫描时,会匹配后面的exists部分,若条件为true,则test1 a里面该条记录符合,很明显,exists部分也即上面“A”里面的结果,很自然最终查询结果有2条记录啦:
t1 d1
--------------
1 1
1 100
--------------------------
count是集合关键字 返回的是一条数据的统计select * from test1 a where exists (select * from test1 where t1=a.t1 GROUP by t1 having count(t1)>1)
这条语句以是吧相等的条件都取出来 你可以这么理解 以count为条件 取出相等的记录