如下面的例子,根据times的排序输出拥有times数值前3位的word。times相同的话算同一等级。这个表名位TE
word  times
a  10
b  13
c  10
d  9
e  2
f  10
g  9
h        5
i        5要求这个例子最后返回的结果应该是
word  times
b  13
a  10
c  10
f  10
d  9
g  9前之前问过别人得到的答案是:
select * from TE a where 3>(Select count(*) From TE where word=a.word and `times`>a.`times`);
不过最后结果不正确。所以重新发帖询问。

解决方案 »

  1.   

    select * from TE a where 3>(select count(distinct times) from  TE where word=a.word and `times`>a.`times`);
      

  2.   

    很可惜,mysql不支持在in的语句里面使用limit,所以只能用下面的语句来代替了。SELECT * 
    FROM te 
    WHERE times =(SELECT DISTINCT times FROM te ORDER BY times DESC LIMIT 0,1) 
       OR times =(SELECT DISTINCT times FROM te ORDER BY times DESC LIMIT 1,1) 
       OR times =(SELECT DISTINCT times FROM te ORDER BY times DESC LIMIT 2,1) 
    ORDER BY times DESC;
      

  3.   


    这是最后的结果,貌似是返回了所有数据....mysql> select * from TE a where 3>(select count(distinct times) from TE where word=a.word and `times`>a.`times`);
    +------+-------+
    | word | times |
    +------+-------+
    | a    |    10 |
    | b    |    13 |
    | c    |    10 |
    | d    |     9 |
    | e    |     2 |
    | f    |    10 |
    | g    |     9 |
    | h    |     5 |
    | i    |     5 |
    +------+-------+
    9 rows in set
      

  4.   

     (不要高估你的汉语表达能力或者我的汉语理解能力)
       建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
       参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
       
       1. 你的 create table xxx .. 语句
       2. 你的 insert into xxx ... 语句
       3. 结果是什么样,(并给以简单的算法描述)
       4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
       
       这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。   
      

  5.   

    CREATE TABLE `te` (
      `word` varchar(255) NOT NULL DEFAULT '',
      `times` smallint(6) DEFAULT NULL,
      PRIMARY KEY (`word`)

    之前不好意思,可能没表达清楚。谢谢!
      

  6.   

    Mysql 5.5.10
    创建数据:INSERT INTO TE VALUES ('a', 10);
    INSERT INTO TE VALUES ('b', 13);
    INSERT INTO TE VALUES ('c', 10);
    INSERT INTO TE VALUES ('d', 9);
    INSERT INTO TE VALUES ('e', 2);
      

  7.   

    mysql> select * from TE a
        -> where 3>(select count(distinct times) from  TE where `times`>a.`times`);
    +------+-------+
    | word | times |
    +------+-------+
    | a    |    10 |
    | b    |    13 |
    | c    |    10 |
    | d    |     9 |
    +------+-------+
    4 rows in set (0.01 sec)mysql>