如何从多个表中获取按时间排序的最后 30 个项目?
我有 3 个表可以从中获取信息:
- 文章
- 发布
- 图片
所有这些表都有“created_at”列。
我想获取按created_at列排序的最后30个项目抛出sql查询, 在最坏的情况下,我将不得不从任何表中弹出 30 个项目,并通过 php 代码从数组中对其进行排序。
I have like 3 tables to get info from them:
- articles
- posts
- pictures
All of this tables have 'created_at' column.
I want to get last 30 items ordered by created_at column throw sql query,
in the worst case i will have to eject 30 items from any table, and order it from array by php code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
像这样的事情怎么样:
这尚未经过测试,但应该可以工作。确保将“*”更改为您正在使用的任何字段。
What about something like this:
This is untested, but should work. Make sure to change "*" to whatever fields you are using.
基于过去的答案,并在此处添加一点优化:
FWIW - 这是未经测试的,可能包含愚蠢的错误。
我首先假设created_at 在所有三个表上都建立了索引。
我还将限制每个表仅返回“最后 30 个项目”,这样我们就不会在可能巨大的派生表(我们无法在其中建立索引)上进行排序。
因此,派生表上的最终“排序依据”保证排序 <= 90 行。
比订购 3 个表的总并集要好得多。
Building on the past answers, and add a little bit of optimization here:
FWIW - this is untested and may contain stupid errors.
I'm first going to assume that created_at is indexed on all three tables.
I'm also going to restrict each table to only returning the 'last 30 items' so we're not ordering on a potentially huge derived table (in which we can't index).
So, the final 'order by' on the derived table is guaranteed to order <= 90 rows.
Much better than ordering the total union of 3 tables.
类似的东西:
几乎可以肯定,您需要将
*
替换为您要选择的两个表共有的字段列表(例如 ID),也许还需要用一些东西来识别它是什么类型的对象(例如,SELECT a, b, 'article' AS item_type
)请小心放置
WHERE
子句的位置。理想情况下,您可以在每个内部选择上放置一个以限制其中包含的对象,而不是在外部放置一个必须等待整个UNION
操作的大量WHERE
要首先执行。Something like:
Almost certainly you will need to replace
*
with the list of fields common to both tables that you want to select (e.g., ID), and perhaps something to identify what type of object it was (e.g.,SELECT a, b, 'article' AS item_type
)Be careful where you put your
WHERE
clauses. Ideally you can put one on each of the inner selects to limit what objects are included there, rather than putting one massiveWHERE
on the outside that must wait for the entireUNION
operation to be performed first.我会选择:
I would go with: