jjzjj

mysql - 避免使用 INNER JOIN + ORDER BY 进行文件排序

coder 2023-10-06 原文

我一直在阅读其他帖子,但未能解决我的问题。

使用 DESC 命令查询速度慢了 x20 倍,我必须改进它。 这是查询:

SELECT posts.post_id, posts.post_b_id, posts.post_title, posts.post_cont, posts.thumb, posts.post_user, boards.board_title_l, boards.board_title
FROM posts
INNER JOIN follow ON posts.post_b_id = follow.board_id
INNER JOIN boards ON posts.post_b_id = boards.board_id
WHERE follow.user_id =1
ORDER BY posts.post_id DESC 
LIMIT 10

这些是表格(已更新):

CREATE TABLE IF NOT EXISTS `posts` (
`post_id` int(11) NOT NULL AUTO_INCREMENT,
`post_b_id` int(11) unsigned NOT NULL,
`post_title` varchar(50) COLLATE utf8_bin NOT NULL,
`post_cont` text COLLATE utf8_bin NOT NULL,
`post_mintxt` varchar(255) COLLATE utf8_bin NOT NULL,
`post_type` char(3) COLLATE utf8_bin NOT NULL,
`thumb` varchar(200) COLLATE utf8_bin NOT NULL,
`post_user` varchar(16) COLLATE utf8_bin NOT NULL,
`published` enum('0','1') COLLATE utf8_bin NOT NULL,
`post_ip` varchar(94) COLLATE utf8_bin NOT NULL,
`post_ip_dat` int(11) unsigned NOT NULL,
`post_up` int(10) unsigned NOT NULL DEFAULT '0',
`post_down` int(10) unsigned NOT NULL DEFAULT '0',
 PRIMARY KEY (`post_id`),
 KEY `post_b_id` (`post_b_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=405 ;

CREATE TABLE IF NOT EXISTS `boards` (
`board_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`board_title_l` varchar(19) COLLATE utf8_bin NOT NULL,
`board_user_id` int(10) unsigned NOT NULL,
`board_title` varchar(19) COLLATE utf8_bin NOT NULL,
`board_user` varchar(16) COLLATE utf8_bin NOT NULL,
`board_txt` tinyint(1) unsigned NOT NULL,
`board_img` tinyint(1) unsigned NOT NULL,
`board_vid` tinyint(1) unsigned NOT NULL,
`board_desc` varchar(100) COLLATE utf8_bin NOT NULL,
`board_mod_p` tinyint(3) unsigned NOT NULL DEFAULT '0',
`board_ip` varchar(94) COLLATE utf8_bin NOT NULL,
`board_dat_ip` int(11) unsigned NOT NULL,
 PRIMARY KEY (`board_id`),
 UNIQUE KEY `board_title_l` (`board_title_l`),
 KEY `board_user_id` (`board_user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=89 ;

CREATE TABLE IF NOT EXISTS `follow` (
`user_id` int(10) unsigned NOT NULL,
`board_id` int(10) unsigned NOT NULL,
 PRIMARY KEY (`user_id`,`board_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

使用默认的 ASC 顺序,它只使用 index 和 whereDESC 使用 index、where、temporary 和 filesort。

id  select_type table   type    possible_keys   key         key_len  ref                rows    filtered    Extra   
 1  SIMPLE      follow  ref     user_id         user_id     4        const              2       100.00      Using index; Using temporary; Using filesort
 1  SIMPLE      boards  eq_ref  PRIMARY         PRIMARY     4   xxxx.follow.board_id    1       100.00  
 1  SIMPLE      posts   ref     post_b_id       post_b_id   4   xxxx.boards.board_id    3       100.00      Using where

如何使查询在没有文件排序和临时的情况下按 DESC 顺序接收结果。

更新:我做了一个新查询,没有临时或文件排序,但类型:索引,过滤:7340.00。如果帖子位于表的末尾,则几乎与 ASC 命令一样快,但如果正在搜索的帖子位于表的开头,则速度较慢。所以看起来更好,但这还不够。

SELECT posts.post_id, posts.post_b_id, posts.post_title, posts.post_cont, posts.thumb, posts.post_user, boards.board_title_l, boards.board_title 
FROM posts INNER JOIN boards ON posts.post_b_id = boards.board_id
WHERE posts.post_b_id
IN (
 SELECT follow.board_id
 FROM follow
 WHERE follow.user_id = 1
)
ORDER BY posts.post_id DESC 
LIMIT 10

解释:

id  select_type        table    type    possible_keys   key        key_len   ref                rows    filtered    Extra   
 1  PRIMARY            posts    index   post_b_id       PRIMARY        8     NULL                10     7340.00    Using where
 1  PRIMARY            boards   eq_ref  PRIMARY         PRIMARY        4    xxxx.posts.post_b_id 1      100.00  
 2  DEPENDENT SUBQUERY  follow  eq_ref  user_id         user_id        8     const,func          1      100.00     Using index

更新:解释来自 dened's answer 的查询:

id  select_type table   type    possible_keys    key       key_len  ref              rows   filtered    Extra   
1   PRIMARY     <derived2>ALL   NULL             NULL      NULL     NULL             10     100.00  
1   PRIMARY     posts   eq_ref  PRIMARY,post_b_id PRIMARY  4        sq.post_id       1      100.00      
1   PRIMARY     boards  eq_ref  PRIMARY          PRIMARY   4    xxxx.posts.post_b_id 1      100.00  
2   DERIVED     follow  ref     PRIMARY          PRIMARY   4                         1      100.00      Using index; Using temporary; Using filesort
2   DERIVED     posts   ref     post_b_id        post_b_id 4    xxxx.follow.board_id 6      100.00      Using index

时间:

Original query no order (ASC):              0.187500 seconds
Original query DESC:                        2.812500 seconds
Second query posts at the end (DESC):       0.218750 seconds
Second query posts at the beginning (DESC): 3.293750 seconds
dened's query DESC:                         0.421875 seconds 
dened's query no order (ASC):               0.323750 seconds 

有趣的是,如果我添加 ORDER BY ASCDESC 一样慢。

改变表格顺序将是一个很好的方式,但正如我在评论中所说,我无法做到这一点。

最佳答案

您可以通过将所有过滤工作转移到仅访问索引的子查询(操作索引通常比操作其他数据快得多)并在最外层查询中获取其余数据来帮助 MySQL 优化器:

SELECT posts.post_id,
       posts.post_b_id,
       posts.post_title,
       posts.post_cont,
       posts.thumb,
       posts.post_user,
       boards.board_title_l,
       boards.board_title
FROM   (SELECT post_id
        FROM   posts
               JOIN follow
                 ON posts.post_b_id = follow.board_id
        WHERE  follow.user_id = 1
        ORDER  BY post_id DESC
        LIMIT  10) sq
       JOIN posts
         ON posts.post_id = sq.post_id
       JOIN boards
         ON boards.board_id = posts.post_b_id

请注意,我从外部查询中省略了 ORDER BY posts.post_id DESC,因为在代码中对最终结果进行排序通常比使用 MySQL 查询排序更快(MySQL 通常使用 < em="">文件排序)。

附言您可以用主键替换 follow 表中的唯一键。

关于mysql - 避免使用 INNER JOIN + ORDER BY 进行文件排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30414641/

有关mysql - 避免使用 INNER JOIN + ORDER BY 进行文件排序的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  7. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  8. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  9. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  10. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

随机推荐