› 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
Ransford
V2EX  ›  MySQL

sql 语句问题,按某列值的记录个数多少 对记录排序,请点进来看详细描述。~

  •  
  •   Ransford ·
    BYRans · Jun 20, 2014 · 5203 views
    This topic created in 4486 days ago, the information mentioned may be changed or developed.
    表名是:help
    id    order
    1     1
    2     1
    3     2
    4     2
    5     2
    6     3

    我想得到:
    id      order
    3     2
    4     2
    5     2
    1     1
    2     1
    6     3

    就是order值多的那组记录在前 降序
    这个sql怎么写啊~~~我用的是mysql
    4 replies  •  2014-06-23 10:34:35 +08:00
    hjse7en
        1
    hjse7en  
       Jun 21, 2014
    SELECT
    a.id,
    a.ord
    FROM order_by_count_test a
    LEFT JOIN (SELECT
    ord,
    count(ord) AS cnt
    FROM order_by_count_test
    GROUP BY ord) AS b
    ON a.ord = b.ord
    ORDER BY b.cnt DESC, a.id;

    不过这种sql效率不怎样。
    hit9
        2
    hit9  
       Jun 21, 2014
    首先,你不能使用order来作为一个列的名字!(sql保留字)

    其实,如果我们使用od来表示order列,那么这个sql可以是(与一楼一样的思路,用左join展开group结果):

    select a.id, a.od from help as a left join (select id, od, count(id) as c from help group by od) as b on a.od=b.od order by c;
    ledkk
        3
    ledkk  
       Jun 21, 2014
    @hit9 保留字 用 `order` 包起来就可以啦
    hit9
        4
    hit9  
       Jun 23, 2014
    @ledkk 对的!^_^
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2346 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 07:32 · PVG 15:32 · LAX 00:32 · JFK 03:32
    ♥ Do have faith in what you're doing.