› MySQL 5.5 Community Server
› MySQL 5.6 Community Server
› Percona Configuration Wizard
› XtraBackup 搭建主从复制
Great Sites on MySQL
› Percona
› MySQL Performance Blog
› Severalnines
推荐管理工具
› Sequel Pro
› phpMyAdmin
推荐书目
› MySQL Cookbook
MySQL 相关项目
› MariaDB
› Drizzle
参考文档
› http://mysql-python.sourceforge.net/MySQLdb.html
buckethead1
V2EX  ›  MySQL

如何得到这个表中某个整形字段第二小的值,不能使用 limit in top 关键字

  •  
  •   buckethead1 · Aug 30, 2015 · 3667 views
    This topic created in 4044 days ago, the information mentioned may be changed or developed.

    用 limit,top,in 我都会写,但是不用的话真想不出来 T_T

    limit

    select x.* from (select * from test order by b limit 2 ) x order by x.b desc limit 1;
    top 和 limit 一样

    in

    select min (b ) from page_test where b not in
    (select min (b ) from page_test );

    已经想了好久了,用 count?还是用高级的函数?

    5 replies  •  2015-08-30 19:30:12 +08:00
    realpg
        1
    realpg  
       Aug 30, 2015   ❤️ 1
    MYSQL:
    select min (xxx ) from table where xxx> (select min (xxx ) from table );
    realpg
        2
    realpg  
       Aug 30, 2015
    更正,你这需求不太明确:

    假设 table 表结构如下
    pk (主键) xxx
    如果值那一列为 1 1 2 3 4 5 6 7 第二小的是 1 还是 2 ?如果单纯按照值来算 第一小的是 1 ,第二小的是 2
    如果按照列排序的方式算,第一小的是 1 第二小的还是 1

    第一种方式:
    select min (xxx ) from `table` where xxx> (select min (xxx ) from `table`);

    第二种方式:
    select min (xxx ) from `table` where xxx>=(select min (xxx ) from `table`) and pk<> (select pk from (select pk,min (xxx ) from `table`) a );
    phx13ye
        3
    phx13ye  
       Aug 30, 2015
    有一道题叫做 Nth Highest Salary ,解法是
    SELECT DISTINCT Salary FROM Employee Emp1 WHERE (N-1 ) = (SELECT COUNT (DISTINCT (Salary ))
    你可以看一下,
    具体思路是,对于这条第二小的记录,肯定有一条记录比他还小
    phx13ye
        4
    phx13ye  
       Aug 30, 2015   ❤️ 1
    没写完整
    SELECT DISTINCT Salary FROM Employee Emp1 WHERE (N-1 ) = (SELECT COUNT (DISTINCT (Salary ))
    FROM Employee Emp2 WHERE Emp2.Salary > Emp1.Salary )
    buckethead1
        5
    buckethead1  
    OP
       Aug 30, 2015
    @phx13ye 谢谢 我就在想这种方法
    select int from table x
    where 1=
    (select count (int ) from table y where y.int < x.int );
    不考虑重复的问题,这样解法就是我一直有思路但是没想出来的 0.0
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1133 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 17:39 · PVG 01:39 · LAX 10:39 · JFK 13:39
    ♥ Do have faith in what you're doing.