V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
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 · 2015-08-30 17:22:50 +08:00 · 2469 次点击
    这是一个创建于 3165 天前的主题,其中的信息可能已经有所发展或是发生改变。

    用 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 条回复    2015-08-30 19:30:12 +08:00
    realpg
        1
    realpg  
       2015-08-30 17:31:51 +08:00   ❤️ 1
    MYSQL:
    select min (xxx ) from table where xxx> (select min (xxx ) from table );
    realpg
        2
    realpg  
       2015-08-30 17:45:18 +08:00
    更正,你这需求不太明确:

    假设 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  
       2015-08-30 18:42:47 +08:00
    有一道题叫做 Nth Highest Salary ,解法是
    SELECT DISTINCT Salary FROM Employee Emp1 WHERE (N-1 ) = (SELECT COUNT (DISTINCT (Salary ))
    你可以看一下,
    具体思路是,对于这条第二小的记录,肯定有一条记录比他还小
    phx13ye
        4
    phx13ye  
       2015-08-30 18:43:55 +08:00   ❤️ 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
       2015-08-30 19:30:12 +08:00
    @phx13ye 谢谢 我就在想这种方法
    select int from table x
    where 1=
    (select count (int ) from table y where y.int < x.int );
    不考虑重复的问题,这样解法就是我一直有思路但是没想出来的 0.0
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5297 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 08:13 · PVG 16:13 · LAX 01:13 · JFK 04:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.