0

假设我在下面有 2 个表:

文章_1

+----------------------------------------+
|id    |  title      |  updated_date     |
+--------------------+-------------------+
|1     |article 1    | 2013/10/4 12:24:00|
+--------------------+-------------------+
|2     |article 2    | 2013/10/2 12:25:00|
+--------------------+-------------------+
|3     |article 3    | 2013/10/3 12:26:00|
+--------------------+-------------------+

文章_2

+----------------------------------------+
|id    |  title      |  updated_date     |
+----------------------------------------+
|1     |article 4    | 2013/10/1 10:24:00|
+----------------------------------------+
|2     |article 5    | 2013/10/5 10:25:00|
+----------------------------------------+
|3     |article 6    | 2013/10/3 10:26:00|
+----------------------------------------+

如何从这 2 个表中检索最新更新的文章?简而言之,如何根据其 updated_date (2013/10/5 10:25:00 是最大更新日期)在articles_2 表中获取“文章5 ”?

提前致谢!

4

2 回答 2

3

使用 SUBSELECT 和 UNION 语句:

SELECT id, title, updated_date, origin
FROM (
    SELECT id, title, updated_date, 'articles_1' AS origin
    FROM articles_1
    UNION ALL
    SELECT id, title, updated_date, 'articles_2' AS origin
    FROM articles_2
) a
ORDER BY updated_date DESC
LIMIT 1

使用“来源”列,您可以知道注册表在哪里

于 2013-10-11T03:21:06.110 回答
2

我不确定为什么你有两个表中包含相同类型的数据,但你可以使用 aUNION将它们放在一起,然后从联合中选择第一行:

SELECT id, title, updated_date
FROM (
    SELECT id, title, updated_date
    FROM articles_1
    UNION ALL
    SELECT id, title, updated_date
    FROM articles_2
) a
ORDER BY updated_date DESC
LIMIT 1

SQL Fiddle 演示

于 2013-10-11T03:04:55.113 回答