【问题标题】:Select n latest rows between two SQLite tables在两个 SQLite 表之间选择 n 个最新行
【发布时间】:2016-06-18 16:52:57
【问题描述】:

我在 SQLite 数据库中有两个表 A 和 B。表 A 如下所示:

|  id  |  name         |  description  |  created     |
|------|---------------|---------------|--------------|
|  1   |  "Something"  |  "Something"  |  1466266963  |
|  2   |  "Something"  |  "Something"  |  1466266965  |
|  3   |  "Something"  |  "Something"  |  1466266967  |
|  4   |  "Something"  |  "Something"  |  1466266969  |
|  5   |  "Something"  |  "Something"  |  1466266971  |
|  6   |  "Something"  |  "Something"  |  1466266975  |

而表B是这样的:

|  id  |  title        |  content      |  created     |
|------|---------------|---------------|--------------|
|  1   |  "Something"  |  "Something"  |  1466266951  |
|  2   |  "Something"  |  "Something"  |  1466266953  |
|  3   |  "Something"  |  "Something"  |  1466266954  |
|  4   |  "Something"  |  "Something"  |  1466266956  |
|  5   |  "Something"  |  "Something"  |  1466266957  |
|  6   |  "Something"  |  "Something"  |  1466266978  |

我想在两张桌子之间找到最老的 4 个。

所以在这个例子中我会得到类似的东西:

|  id  |  title        |  name         |  content      |  description  |  created     |
|------|---------------|---------------|---------------|---------------|--------------|
|  6   |  "Something"  |               |  "Something"  |               |  1466266975  |
|  6   |               |  "Something"  |               |  "Something"  |  1466266975  |
|  5   |               |  "Something"  |               |  "Something"  |  1466266975  |
|  4   |               |  "Something"  |               |  "Something"  |  1466266975  |

我尝试了SELECT A.*, B.* FROM A, B ORDER BY created DESC LIMIT 4,但结果为空(不过我的表不是空的)。

我也查看了 JOIN,但没有成功。

有什么想法吗?谢谢。

【问题讨论】:

    标签: sqlite select multiple-tables


    【解决方案1】:

    使用union all

    select * from(
    select * from a
    union all
    select * from b
    ) t
    order by created DESC LIMIT 4
    

    【讨论】:

    • 我得到那个错误:Unable to prepare statement: no such column: created 尽管created 列确实存在于两个表中,为什么?
    • 从该查询中获得哪些列:select * from a union all select * from b
    • 哦,是的,我没有选择第二个select 中的created 列,我现在工作,谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 2020-03-13
    • 2013-02-23
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多