MySql 查询同一张表的贷方和借方

问题描述 投票:0回答:4

我有一个 MySql 表来控制借方和贷方。而且看起来是这样的

id | status | type  | amount | value | expiration | parent_id | company_id |
---|--------|------ |--------|-------|------------|-----------|------------|
1  |    1   |credit | 46     | 42.00 | 2018-04-01 | 0         | 1          |
2  |    1   |credit | 33     | 194.00| 2017-07-07 | 0         | 1          |
3  |    1   |credit | 49     | 17.00 | 2016-11-11 | 0         | 1          |
4  |    1   |debit  | 1      | NULL  | NULL       | 1         | 1          |
5  |    1   |debit  | 1      | NULL  | NULL       | 1         | 1          |
6  |    1   |debit  | 1      | NULL  | NULL       | 2         | 1          |
7  |    1   |debit  | 1      | NULL  | NULL       | 2         | 1          |
8  |    1   |debit  | 1      | NULL  | NULL       | 2         | 1          |
9  |    1   |debit  | 1      | NULL  | NULL       | 2         | 1          |
10 |    1   |debit  | 1      | NULL  | NULL       | 3         | 1          |

我想检索一个人现在有多少学分。

对状态 = 1 且到期 > NOW() 的每个父贷方计算状态 = 1 的所有借方的总和

然后从其父信用中减去

在这种情况下我应该得到这样的东西

总学分 = (46 - 2) + (33 - 4)

到目前为止我得到的是

SELECT SUM(amount) as tot_debit 
FROM credits
WHERE company_id = 1 
      AND status = 1 
      AND type = 'debit' 
      AND parent_id IN (SELECT id
                         FROM credits 
                         WHERE company_id = 1 
                           AND status = 1 
                           AND expiration > NOW() 
                           AND type = 'credit') 
GROUP BY parent_id

关于如何让它发挥作用有什么想法吗?

谢谢

php mysql sql
4个回答
1
投票

您可以使用相关来获得预期结果:

SELECT SUM(amount) 
       -
       COALESCE((SELECT SUM(amount)
                 FROM credits AS c2
                 WHERE company_id = 1 AND status = 1 AND 
                       type = 'debit' AND
                       c2.parent_id = c1.id), 0)
FROM credits AS c1
WHERE company_id = 1 AND status = 1 AND 
      type = 'credit' AND expiration > NOW();

演示在这里


0
投票

您应该使用自左连接,以便每个记录与其父记录(如果存在)匹配并过滤掉过期记录。然后,通过有条件的总和,您可以添加贷方并减去借方。

SELECT  SUM(CASE WHEN type = 'credit' THEN amount ELSE amount * -1 END) AS total
FROM    credits t1
LEFT JOIN
        credits t2
ON      t1.parent_id = t2.id AND
        t2.expiration > NOW()
WHERE   t1.company_id = 1 AND 
        t1.status = 1 AND
        t1.expiration > NOW()

0
投票

由于您在一张表中同时拥有贷方和借方(我不会推荐这种设计),这里最快的方法可能是聚合:

select sum(total)
from
(
  select 
    sum(case when type = 'credit' then value else -value end) as total
  from mytable
  where company_id = 1
  and status = 1
  group by case when type = 'credit' then id else parent_id end -- group by credit ID
  having sum(type = 'credit' and expiration > now()) > 0
) total_per_credit;

HAVING
子句在 MySQL 中使用 true = 1 / false = 0。 (在其他 DBMS 中,您可以使用
CASE
构造。)


0
投票

1

我正在研究如何在我的 Unity 游戏中获得每日奖励。我见过两种方法:一种是使用手机日期,另一种是使用服务器日期。第一种很容易实现,但很容易被欺骗,第二种需要使用服务器。有没有一种简单的方法可以实现每日奖励而又不允许玩家作弊并且不使用服务器?谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.