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

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

  •  
  •   Ransford ·
    BYRans · 2014-06-20 20:35:56 +08:00 · 4315 次点击
    这是一个创建于 3606 天前的主题,其中的信息可能已经有所发展或是发生改变。
    表名是: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 条回复    2014-06-23 10:34:35 +08:00
    hjse7en
        1
    hjse7en  
       2014-06-21 00:12:31 +08:00
    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  
       2014-06-21 11:23:27 +08:00
    首先,你不能使用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  
       2014-06-21 21:12:31 +08:00
    @hit9 保留字 用 `order` 包起来就可以啦
    hit9
        4
    hit9  
       2014-06-23 10:34:35 +08:00
    @ledkk 对的!^_^
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1581 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 16:27 · PVG 00:27 · LAX 09:27 · JFK 12:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.