【问题标题】:How to get latest N entries from two tables in a database?如何从数据库中的两个表中获取最新的 N 个条目?
【发布时间】:2020-10-26 12:54:46
【问题描述】:

我正在尝试使用烧瓶制作一个项目来跟踪用户的费用。

我在数据库中有两个表.. 收入和支出
收入表有 user_id,income,datetime_utc 作为列

费用表有 user_id,expense_amt,description,datetime_utc 作为列。

我想向用户展示与网络应用程序的最新 N=10 笔交易,即他/她添加到数据库中的最近 10 笔费用和收入金额。

为此,我必须比较两个表的 datetime_utc 列,以找出哪一个是最新的 N 个条目

而且我似乎没有找到这样做的逻辑:(
这个逻辑有什么帮助吗??
注意:我正在使用 orm flask_sqlalchemy 但将不胜感激 sql 答案

【问题讨论】:

  • 问题不清楚,所以投票结束。表在列中不匹配,并且没有预期的结果来执行有根据的猜测。

标签: python sql postgresql flask


【解决方案1】:

假设它们具有相同的数据结构,那么:

select ie.*
from ((select i.* 
       from income i
       where user_id = ?
       order by i.datetime_utc desc
       limit 10
      ) union all
      (select e.* 
       from expense e
       where e.user_id = ?
       order by e.datetime_utc desc
       limit 10
      )
     ) ie
order by datetime_utc desc
limit 10;

内部查询为给定用户选择 10 个最近的收入和支出交易。然后外部查询在其中选择 10 个。

【讨论】:

  • 两个表的列数不同,所以你认为 union all 会起作用吗???
  • @BinitDhakal 。 . .不,这行不通。然后,您需要明确列出您想要的每个表中的列。
  • 我想我必须使列数相同谢谢您的指导@GordonLinoff
【解决方案2】:

这将为您提供 两个 表中的最新 10 笔交易。正如@TheImpaler 所指出的,当所有结果条目都来自同一个表时,两个联合子查询都限制为 10 个条目,以防万一。

with t (user_id, amount, datetime_utc, transaction_type) as 
(
 select user_id, income, datetime_utc, 'income'::text from income
   where user_id = $1 order by datetime_utc desc limit 10
 union
 select user_id, expense_amt, datetime_utc, 'expense' from expense
   where user_id = $1 order by datetime_utc desc limit 10
) 
select * from t order by datetime_utc desc limit 10;

【讨论】:

    猜你喜欢
    • 2014-09-11
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    相关资源
    最近更新 更多