【问题标题】:Insert multiple row with condition checking on other table.. only single query在其他表上插入多行并进行条件检查..只有单个查询
【发布时间】:2017-02-09 11:47:38
【问题描述】:

表 1:用户管理员

uid uname
1    abc
2    xyz
3    pqr
4    def

表 2:事务主管

tid uid amount type
1    1  100    1
2    2  500    1
2    2  500    2
3    1  350    1
3    1  150    2

输入事务表:

1 for capital
2 for interest(5% of total capital)

现在,我想计算每个月的资本金额interest 和资本价值 5% 的广告利息。 应通过以下查询:transactionmaster 表中自动为两个有资本的用户添加兴趣条目

transactionmaster 表中的结果应该是这样的。

tid uid amount type
1    1  100    1
2    2  500    1
3    1  600    1
4    1  35     2
5    2  25     2

这里interest 也自动计算 5%。

【问题讨论】:

标签: php mysql multirow


【解决方案1】:

要在每个月自动获取结果,您需要使用 MySQL 事件安排 SQL 查询。

这是参考 1)http://www.infotuts.com/schedule-sql-query-using-phpmyadmin-mysql-events/

从 transactionmaster 获取资金总和

select sum(amount) from transactionmaster where uid = 13 and type=1

现在计算利息

select sum(amount) * (5 / 100)  as interest from transactionmaster where uid=13 and type=1

简单!

【讨论】:

    【解决方案2】:

    这样的事情应该可以解决问题:

    INSERT INTO transactionmaster (uid, amount, type)
    SELECT uid, ((SUM(amount) / 100) * 5), 2
    FROM transactionmaster
    WHERE type = 1 
    GROUP BY uid
    

    我假设tid 字段是一个自动增量


    编辑: 上面的查询是一次性的。即,它将系统地为所有具有“类型 1”的 uid 创建“类型 2”条目。换句话说,如果你多次使用它,你最终会得到重复的“类型 2”条目。

    如果您只想为“type 1”插入“type 2”行,而“type 1”还没有“type 2”行,您可以这样做:

    INSERT INTO transactionmaster (uid, amount, type)
    SELECT t1.uid, ((SUM(t1.amount) / 100) * 5), 2
    FROM transactionmaster t1 
    LEFT JOIN transactionmaster t2 ON t1.uid=t2.uid AND t1.type=1 AND t2.type=2 
    WHERE t2.tid IS NULL
    GROUP BY t1.uid
    

    编辑 2 以回答您的评论。

    假设您创建了一个具有这种结构的 intrustmaster 表:

    loweramt | higheramt | perc
    ---------------------------
    100      | 199       | 5
    200      | 399       | 4
    

    oneshot 查询会变成这样:

    INSERT INTO transactionmaster (uid, amount, type)
    SELECT T.uid, ((totamt /100) * i.perc), 2
    FROM 
    (
        SELECT uid, (SUM(amount) / 100) as totamt
        FROM transactionmaster
        WHERE type = 1 
        GROUP BY uid
    ) T
    INNER JOIN intrustmaster I
      ON t.totamt BETWEEN i.loweramt AND i.higheramt
    

    【讨论】:

    • 让我在这里建议一件事,如果每个阶段的信任都不同,那怎么可能,假设我制作了一张桌子 intrustmaster 并且有 3 个平板,100-200 信任是 5%,200-400 信任是 4% 和 500-1000 5% 那么需要什么改变?
    • 100-200 和 200-400 是一个 uid 的总量吗?
    • 是的,uid、intrustmaster 字段(id、min、max、intrust_rate)的总量。数据(1,100,200,5)(2,201,400,4)(3,401,500,5)
    • 已回答,但像这样闲聊并不是对 SO 进行问答的正确方式。因此,如果您还有其他问题,请编辑您的答案并添加详细信息,或者创建一个包含更多具体元素的新问题。
    猜你喜欢
    • 2021-10-19
    • 1970-01-01
    • 2019-10-04
    • 2013-06-16
    • 2014-06-04
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 2013-10-31
    相关资源
    最近更新 更多