这个查询没有返回我所期望的结果。为什么?
下表:
create table t
(
comment varchar(10),
id int
);数据:
insert into t values ('C1', 1);
insert into t values ('C2', 2);
insert into t values ('C3', 3);
insert into t values ('C4', 4);
insert into t values ('C5', 5);
insert into t values ('C6', 6);
insert into t values ('C7', 7);
insert into t values ('C8', 8);
insert into t values ('C9', 9);
insert into t values ('C1', 10);查询:
select distinct comment from t order by id desc limit 8;结果是:
C9
C8
C7
C6
C5
C4
C3
C2当我把DISTINCT去掉时,我得到了最后一行,但我想抑制重复项。我的解决方法返回正确的结果集:
select comment from t group by comment order by max(id) desc limit 8;但是我很好奇我的查询是否无效(例如,T-SQL不允许在一个查询中同时使用DISTINCT和ORDER BY,除非有序列在select列表中)?
发布于 2013-09-12 04:10:59
我猜,只是猜测,C1不在选择范围内,因为它有一个副本,而且我猜它SQL -select这个副本的id是10而不是1。这就是为什么你得到的id是从2到9(总共8个,就像你从SQL中问到的限制8一样)。请检查一下我的理论是否正确。我猜它的工作流程就像id为1的记录,ok no dupes,next,id2,no dupes,ok...,id 10 -是id 1的副本,删除id 1的记录,添加id为10的记录……
https://stackoverflow.com/questions/15261343
复制相似问题