Select 两个表中的最新条目?

Select the latest entry from two tables?

现在标题可能有点乱,三言两语难以解释。

所以我有 table 个主题和帖子。两者都有 "posted" 行,表示 thread/post 发布的时间。我需要做的是比较这些并只选择一个条目,该条目是最新的。

我可以证明我的意思。我现在有这个。

$postsQ = $DB->query("SELECT t.posted, p.userid, p.topicid, t.id FROM posts p, topics t WHERE t.forumid = '$ForumSub[id]' AND t.id = p.topicid ORDER BY t.posted DESC LIMIT 1,1");

这不是我所知道的最好的代码。

我知道这行不通,但为了展示我想要的想法,下面是查询的外观

$postsQ = $DB->query("SELECT (p.posted AND t.posted) AS tpposted, p.userid, p.topicid, t.id FROM posts p, topics t WHERE t.forumid = '$ForumSub[id]' AND t.id = p.topicid ORDER BY tpposted DESC LIMIT 1,1");

有人知道我怎样才能做到这一点吗?

您可以简单地将表的同质化版本合并在一起,然后按 posted 降序对它们进行排序并限制结果。试试这个:

select *
  from
    (
      select id, posted, userid, 'post'
        from posts
      union
        select id, posted, userid, 'topic'
          from topics
    ) q
  order by posted desc limit 1;

这里有演示fiddle:http://sqlfiddle.com/#!9/b46c2/1