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

求一个多条件查询,每个条件都能查询指定数量的结果的语句

  •  
  •   kaiki · 2022-11-15 18:44:24 +08:00 · 1201 次点击
    这是一个创建于 498 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如:从 group 为 1 、2 、3 的条件中查询 point 前 3 的项目的数据,这样就可以查询出 9 条数据了,能一条语句搞定吗?

    9 条回复    2022-11-16 00:28:25 +08:00
    ackoly
        1
    ackoly  
       2022-11-15 19:43:06 +08:00 via iPhone
    什么数据库,分析函数了解一下
    optional
        2
    optional  
       2022-11-15 19:49:07 +08:00
    row_number over partition by 一下,再套个子查询或者 cte ,完事
    wolfie
        3
    wolfie  
       2022-11-15 19:53:48 +08:00   ❤️ 1
    kwh
        4
    kwh  
       2022-11-15 20:05:48 +08:00   ❤️ 1
    select * from table where group=1 order by point desc limit 3
    union
    select * from table where group=2 order by point desc limit 3
    union
    select * from table where group=3 order by point desc limit 3
    dqzcwxb
        5
    dqzcwxb  
       2022-11-15 20:26:03 +08:00
    并行查三次是最终答案
    wxf666
        6
    wxf666  
       2022-11-15 20:42:18 +08:00
    @dqzcwxb 请教一下,为嘛不选用窗口函数呢?(差在哪儿?)
    bugfan
        7
    bugfan  
       2022-11-15 20:45:12 +08:00
    老哥这头像真帅~~
    kaiki
        8
    kaiki  
    OP
       2022-11-15 21:00:37 +08:00
    @wolfie 感谢,文章很有帮助
    @kwh 合并查询的确可以,谢谢
    dqzcwxb
        9
    dqzcwxb  
       2022-11-16 00:28:25 +08:00
    @wxf666 #6 没法做缓存,把性能压力交给数据库不是一个能长久的方案
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3712 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:40 · PVG 18:40 · LAX 03:40 · JFK 06:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.