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

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