简体   繁体   English

从两个表中选择具有不同字段名称的时间戳,然后对其排序?

[英]Select timestamps with different field names from two tables, and order them?

I've looked at some other questions here but can't find a solution that matches mine. 我在这里查看了其他一些问题,但找不到与我匹配的解决方案。 I don't really understand some of the parts so I can't adapt their solutions to my problem. 我不太了解其中的某些部分,因此无法适应他们的问题。

I have a table like this: 我有一张这样的桌子:

post_id, post_author, post_message, post_timestamp, post_thread and.. thread_id, thread_author, thread_message, thread_timestamp and I'd like to fetch * from both (different) tables, and order by their timestamp so I could fetch the latest from both. post_id, post_author, post_message, post_timestamp, post_threadpost_id, post_author, post_message, post_timestamp, post_thread thread_id, thread_author, thread_message, thread_timestamp ,我想从两个(不同的)表中获取*,并按其时间戳排序,以便从两者中获取最新的。

How can I achieve this? 我该如何实现? As I said I looked into some other solutions here but can't adapt it as the ones I can find, have the same name on their timestamp field. 正如我说的,我在这里研究了其他一些解决方案,但无法适应我所找到的解决方案,它们的时间戳字段名称相同。

Thanks in advance. 提前致谢。

You're going to want to use a LEFT JOIN from thread to post, and you can sort using a coalesce . 您将要使用从线程到帖子的LEFT JOIN ,并且可以使用coalesce进行排序。 The performance will probably be horrible, but let's get something working first and then tune it. 性能可能会很糟糕,但是让我们先进行一些工作,然后对其进行调整。

SELECT p.*, t.*, coalesce(p.post_timestamp, t.thread_timestamp) as timestamp FROM thread t
LEFT JOIN (SELECT * FROM post ORDER BY post_timestamp DESC LIMIT 1) as p on p.post_thread = t.thread_id
ORDER BY timestamp DESC
LIMIT 10
;

The coalesce function takes a list of arguments and returns the first one that's not null. coalesce函数采用参数列表,并返回第一个非null的参数。 So in this case, it will return the post timestamp, unless there is no post, in which case it will return the thread timestamp. 因此,在这种情况下,它将返回发布时间戳,除非没有发布,在这种情况下,它将返回线程时间戳。 The join is a LEFT join so that even if the subselect returns zero results, there will still be a result row. 该联接是LEFT联接,因此,即使子选择返回零结果,仍然会有一个结果行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM