MySQL-选择+加入+按性能排序

发布于 2024-10-05 12:57:27 字数 719 浏览 1 评论 0原文

我有两个表,我需要从两个表中选择一些连接的数据

SELECT f.* 
FROM file_data f
JOIN subscriptions s ON f.uid = s.elementid
WHERE s.uid = 119762 AND f.private=0  
ORDER BY f.date DESC

现在,即使对于一小部分数据,查询也需要一秒钟以上的时间。 这是由于“订阅”上使用了“文件排序”和“临时”,由 ORDER BY f.date 引起(删除该条件会导致时间降至 0.01 秒以下)

谁能告诉我如何加快查询速度?

这是 EXPLAIN 的结果

id  select_type    table    type   possible_keys    key            key_len  ref           rows  Extra
1    SIMPLE         s        ref    uid_elementid    uid_elementid  4        const         171   Using index; Using temporary; Using filesort
1    SIMPLE         f        ref    uid_uname        uid_uname      5        s.elementid   22    Using where

I'm having two tables, I need to select some data joined from both of them

SELECT f.* 
FROM file_data f
JOIN subscriptions s ON f.uid = s.elementid
WHERE s.uid = 119762 AND f.private=0  
ORDER BY f.date DESC

Now, even for a small set of data the query takes over a second.
This is due to 'filesort' and 'temporary' used on "subscriptions", caused by ORDER BY f.date (removing that condition causes the time to drop under 0.01s)

Can anyone tell me how to speed up the query?

Here's the result of EXPLAIN

id  select_type    table    type   possible_keys    key            key_len  ref           rows  Extra
1    SIMPLE         s        ref    uid_elementid    uid_elementid  4        const         171   Using index; Using temporary; Using filesort
1    SIMPLE         f        ref    uid_uname        uid_uname      5        s.elementid   22    Using where

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清泪尽 2024-10-12 12:57:27

索引何时有助于排序依据是很难预测的。它很少像“按 order by 对字段进行索引”那么简单。 此链接包含详细信息。如果您认为自己有正确的索引,而优化器只是不决定使用它们,请使用 索引提示,向数据库服务器建议索引。

When an index will help an order by is non-trivial to predict. It is very rarely as simple as "index the fields in the order by". This link has the nitty-gritty details. If you think you have proper indexing and the optimizer just isn't deciding to use them, use an index hint to suggest the index to the database server.

浪推晚风 2024-10-12 12:57:27

你应该在 f.date 上放置一个索引

You should put an index on f.date

强者自强 2024-10-12 12:57:27

我遇到了同样的问题,这是我的解决方案:

SELECT f.* 
FROM (SELECT * FROM file_data WHERE `private`=0 ORDER BY `date` DESC ) f
JOIN subscriptions s ON f.uid = s.elementid
WHERE s.uid = 119762

I met the same problem,this is my solution:

SELECT f.* 
FROM (SELECT * FROM file_data WHERE `private`=0 ORDER BY `date` DESC ) f
JOIN subscriptions s ON f.uid = s.elementid
WHERE s.uid = 119762
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文