日期:2014-05-19  浏览次数:20548 次

SQL语句Select出现问题,请大家进来帮忙看看!
表名:keyword
字段  
id   主键   标识
nsid     nvarchar(50)
directory   nvarchar(50)
count         int        

select   top   1   id   from   keyword   where   id   not   in(select   top   "   +   TopId   +   "   id   from   keyword   where   nsid= '11 '   and   directory= '1 ')     and   nsid= '11 '   and   directory= '1 '

这句是我要的结果,查询出来是完全正确的。
现在我想加个条件就是   order   by   count   desc

然后我就改成:
select   top   1   id   from   keyword   where   id   not   in(select   top   "   +   TopId   +   "   id   from   keyword   where   nsid= '11 '   and   directory= '1 '   order   by   count   desc)     and   nsid= '11 '   and   directory= '1 '   order   by   count   desc

这样查询后如果count的值都不一样就没问题,如果count的值一样就会重复查询上次一样的id

比如有数据:
id     count
54       1
55       1
56       1
57       1
58       3
59       0

正确的排序查询出来应该是
id     count
58       3
54       1
55       1
56       1
57       1
59       0

可是现在竟然查出来竟然是

id     count
58       3
54       1
54       1
54       1
54       1
59       0

请大家帮忙看看是哪里写错了。谢谢!

------解决方案--------------------
select top 1 id from keyword where id not in(select top " + TopId + " id from keyword where nsid= '11 ' and directory= '1 ' order by count desc) and nsid= '11 ' and directory= '1 ' order by count desc

-------------
這個只會得到1條數據,你的結果怎麼有6條數據?
------解决方案--------------------
narchar 也不+N ...
------解决方案--------------------
dyjqk(http://www.news24h.cn), 你代碼不貼全的,光那一條語句,當然只有1條數據。

而且你這個循環應該得到的是你第一列的結果,那個結果是正常的。


------解决方案--------------------

select top 6 id from keyword where nsid= '11 ' and directory= '1 ' order by count desc

這樣不就是你的結果了?
------解决方案--------------------
再加上一個排序字段試下

select top 1 id from keyword where id not in(select top " + TopId + " id from keyword where nsid= '11 ' and directory= '1 ' order by count desc, id) and nsid= '11 ' and directory= '1 ' order by count desc, id