drmcm84800 2017-03-24 08:23
浏览 52
已采纳

在Laravel 5.4中使用多个表连接处理数百万行的高效且交易安全的方法

This does not necessarily apply only to the Laravel php framework as I believe my intended tasks can be processed on the MySQL server itself as well with appropriate SQL statements.

There are 3 tables as following:

users (>2 million rows)

  • id
  • name
  • balance (decimal, 14, 2)
  • package_id

packages (5 rows)

  • id
  • name
  • value (decimal, 14, 2)
  • percent (decimal, 5, 2) - stored as 0.10 instead of 10

transactions (log)

  • id
  • user_id
  • description
  • amount

All of the tables above are linked to the objects/models User, Package, and Transaction respectively. They contain timestamp columns and are inserted/updated automatically by Laravel.

  1. The application is scheduled to update the column balance in table users based on the value of package (that is assigned to the user) multiplied by percent field plus the original balance value, every day at midnight 12:00am. A clearer expression would be:

    users.balance = users.balance + (packages.value * packages.percent)

  2. At the same time, a transaction log for each balance update should be inserted to the database:

    user_id: [user's id]
    description: Updated user [user's name] with new balance
    amount: [amount added]

I have managed to achieve the first operation with the following SQL statements:

UPDATE users 
INNER JOIN packages 
ON users.package_id = packages.id
SET users.balance = users.balance + (packages.value * packages.percent);

I can't seem to find any solution to achieve both operations at the same time with highest efficiency and transaction-safe. I could possibly retrieve both users and packages and process them in the application then do UPDATEs and INSERTs, but it'd be a no-brainer thing to do as it's really inefficient.

I'd appreciate if someone could help me with the solution!

  • 写回答

2条回答 默认 最新

  • drnl10253 2017-03-24 21:43
    关注

    I don't see any possible way to update or insert on two different tables in mysql. I know of updating 2 different tables with one query but not insert and update on 2 different tables. I think you can use triggers to achieve what you want

    CREATE TRIGGER insert_into_logs_when_user_balance_update
    AFTER UPDATE ON users 
    FOR EACH ROW
      IF NEW.balance <> OLD.balance
      then
        insert into logs(user_id, description, amount)
        values(New.id, New.balance, New.balance)
      END IF
    

    This will update logs tables when users.balance changes/update.

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥15 看一下OPENMV原理图有没有错误
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常
  • ¥15 Java,消息推送配置
  • ¥15 Java计划序号重编制功能,此功能会对所有序号重新排序,排序后不改变前后置关系。
  • ¥15 关于哈夫曼树应用得到一些问题