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

原来 sql 可以这么写!

  •  
  •   HackerJax · Aug 1, 2023 · 4533 views
    This topic created in 1150 days ago, the information mentioned may be changed or developed.
    # 统计 a > b 的行数


    ## ✅:
    ### select count(a > b) from t;


    ## ❌:
    ### select sum(if(a > b, 1, 0)) from t;
    16 replies  •  2023-08-02 16:55:15 +08:00
    AoEiuV020JP
        1
    AoEiuV020JP  
       Aug 1, 2023
    如果效率更高了的话我会怀疑数据库引擎的质量,
    Masoud2023
        2
    Masoud2023  
       Aug 1, 2023   ❤️ 1
    该写的 where 不写,敢这么写 SQL 我要是老板你第二天不用来了
    fkdog
        3
    fkdog  
       Aug 1, 2023
    @Masoud2023 都什么逻辑?
    count 带条件的写法在有带 group by 的查询语句里不是很常见?
    Masoud2023
        4
    Masoud2023  
       Aug 1, 2023
    @fkdog #3 可读性不太好,非必要我绝对不会这么写
    fkdog
        5
    fkdog  
       Aug 1, 2023   ❤️ 1
    @Masoud2023 那说明你写的少呗. 平时业务不涉及到复杂统计需求.
    silencil
        6
    silencil  
       Aug 1, 2023
    不是第一个可读性更好吗?
    yinmin
        7
    yinmin  
       Aug 1, 2023 via iPhone   ❤️ 5
    ## ✅:
    ### select count(*) from t where a>b
    wxf666
        8
    wxf666  
       Aug 1, 2023
    怎么我感觉,你想写的是:select sum(a > b) from t ?
    zzvgtiger
        9
    zzvgtiger  
       Aug 1, 2023
    又学到了一个新知识,哈哈
    Saturn72
        10
    Saturn72  
       Aug 1, 2023
    你这么写 a 和 b 相等时怎么算 我测 a=b 也会计数啊
    via
        11
    via  
       Aug 1, 2023 via iPhone
    抱歉上面的例子少了一个 group by

    ps:我的 id 是 op subaccount
    niumeme
        12
    niumeme  
       Aug 2, 2023
    @yinmin
    正解,因为 where 先执行而 select 后执行,where 可以预先过滤更多的数据,等等我怎么感觉没什么区别
    freemoon
        13
    freemoon  
       Aug 2, 2023
    1. 哪个睿智 boy 会用到第二种写法?莫非是楼主
    2. 第一种写法算是一种奇技淫巧,不常见,可读性对比常规 where 写法差不多
    niumeme
        14
    niumeme  
       Aug 2, 2023
    @lasuar
    第二种写法有第二种写法的好处,比如需要多种筛选条件,我做的消费统计规则比较复杂,很多地方都使用了第二种方法,不在 where 过滤数据是因为有重复的统计
    freemoon
        15
    freemoon  
       Aug 2, 2023
    @lemonteacode #14 贴个示例
    troywinter
        16
    troywinter  
       Aug 2, 2023
    不建议在 OLTP 里这么搞,除非你对这个 execution plan 有清晰的预估,知道会扫描多少行数,复杂度是怎样的,不然这就是给自己挖坑
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   853 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 21:09 · PVG 05:09 · LAX 14:09 · JFK 17:09
    ♥ Do have faith in what you're doing.