表中就两个字段,name 和 id,我想查询出name不同的记录:
select name,(select id from table1 t where t.name = a.name and rownum < 2) id from table1 a;
——这样写不好使,name相同的记录还是会列出来
select name,(select id from table1 t where t.name = a.name and rownum < 2) id from table1 a group by name;
——加了group by name后结果正确;请教下为什么要加group by name,我觉得第一条语句已经能达到效果了,可为什么不好使?
谢谢~!
select name,(select id from table1 t where t.name = a.name and rownum < 2) id from table1 a;
——这样写不好使,name相同的记录还是会列出来
select name,(select id from table1 t where t.name = a.name and rownum < 2) id from table1 a group by name;
——加了group by name后结果正确;请教下为什么要加group by name,我觉得第一条语句已经能达到效果了,可为什么不好使?
谢谢~!
第一句没有group by分组,就相当于在整个表范围内查询,所以有重复的name;
第二句按name分组,(select id from table1 t where t.name = a.name and rownum < 2)的范围变成了每个不同的name,这样就查询出name不同的记录了
——这样写不好使,name相同的记录还是会列出来
group by 只是为了去重复而已
如果你的第一句就能达到效果,没哟重复数据,就没必要group by 了
重复的是name,而不是那个子查询
这个是会列出重复的记录的第二条用group by已经去除了重复记录,然后选出的结果集在来做id的子查询而第一条,结果集已经先返回所有的记录了。
如果在第一句加个distinct也可以
where not exists(select 1 from table1 b where a.name=b.name and a.id=b.id);