简体   繁体   English

PostgreSQL中两个表之间的差异查询?

[英]difference query between two tables in Postgresql?

In Postgresql I have table of items as follow: 在Postgresql中,我的items表如下:

id  qty 
1    20
2    45
3    10

it contains the quantity of each product. 它包含每种产品的数量。 I'm doing a counting operation. 我正在进行计数操作。 For every item I count I copy the data to aa log_count table. 对于我计数的每个项目,我都将数据复制到一个log_count表中。 Items table NEVER CHANGED. 项目表从不改变。

I want to write a query which will show me the difference between the tables. 我想写一个查询,向我显示表之间的区别。 Basically how much left to pass over. 基本上剩下多少要过去。 When the quantity is 0 the row disappears. 当数量为0时,该行消失。

This is how it should be: 这应该是这样的:

Start : 开始

items:             log_count:              QUERY SHOW:
    1    20                                1        20
    2    45                                2        45
    3    10                                3        10

after doing count of: id=1 qty=3 经过计数后: id=1 qty=3

items:             log_count:              QUERY SHOW:
    1    20         1      3               1        17
    2    45                                2        45
    3    10                                3        10

later, after doing count of: id=2 qty=45 稍后,在计数: id=2 qty=45

items:             log_count:              QUERY SHOW:
    1    20         1      3               1        17
    2    45         2      45              3        10
    3    10                                * row of id 2 is gone as its qty=0

later, after doing count of: id=1 qty=2 稍后,在进行以下计数之后: id=1 qty=2

items:             log_count:              QUERY SHOW:
    1    20         1      5               1        15
    2    45         2      45              3        10
    3    10                               

Final stage... 最后阶段

items:             log_count:              QUERY SHOW:
    1    20         1      20             
    2    45         2      45             
    3    10         3      10                      

How do I write this query? 如何编写此查询?

Looks like a simple join to me: 对我来说似乎很简单:

select it.id, it.qty - lc.qty as difference
from items it
  left join log_count lc on it.id = lc.id 
where it.qty - lc.qty > 0;

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

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