写了一个购买商品的功能,购了三个商品执行了 15 次查询,正常吗

写了一个购买商品的功能,大概逻辑就是:

  • 查询商品是否存在,
  • 创建一个总订单
  • 创建最小订单(存一下商品的价格 * 数量)
  • 查一下会员表,看看是否是会员,计算下折扣
  • 查一下代理商表,计算下折扣
  • 把总订单的价格更新一下
  • 查一下小订单的表,用来做数据返回

然后看了一下查询日志,一查执行了 15 条 sql,感觉太多了,但是看一看又觉得没有不必要的查询,请问各位有什么更好的设计或解决方案吗,或者说是正常现象?

execution time: 2ms; select * from `users` where `api_token` = "X7BC0pCz6BTAxd4HhHyBD" limit 1      
execution time: 1ms; select * from `commodities` where `commodities`.`id` = "1" limit 1      
execution time: 0ms; select * from `commodities` where `commodities`.`id` = "2" limit 1      
execution time: 0ms; select * from `commodities` where `commodities`.`id` = "3" limit 1      
execution time: 0ms; select * from `shipping_addresses` where `shipping_addresses`.`user_id` = "1" and `shipping_addresses`.`user_id` is not null order by `default` desc, `id` desc limit 1      
execution time: 3ms; insert into `total_orders` (`user_id`, `address`, `remark`, `delivery_method`) values (...)      
execution time: 3ms; insert into `orders` (`commodity_id`, `amount`, `commodity_title`, `commodity_image`, `price`, `total_order_id`) values (...)
execution time: 2ms; insert into `orders` (`commodity_id`, `amount`, `commodity_title`, `commodity_image`, `price`, `total_order_id`) values (...)
execution time: 0ms; select * from `agents` where `user_id` = "1" and `status` = "normal" limit 1      
execution time: 0ms; select * from `users` where `users`.`id` = "1" limit 1
execution time: 0ms; select * from `members` where `members`.`id` = "1" limit 1      
execution time: 2ms; update `total_orders` set `total_amount` = "23940", `is_agent_order` = "", `use_discount` = "1" where `id` = "108"
execution time: 0ms; select * from `users` where `users`.`id` = "1" limit 1      
execution time: 1ms; select * from `orders` where `orders`.`total_order_id` = "108" and `orders`.`total_order_id` is not null order by `id` desc      

User 表相同是数据查了两次,但是看一下并不知道是在哪里查询的,难道说 Auth::id() 也会查询一次 User 表嘛
shu

死宅,在『什么都不会还异常淡定』和『未来一片迷茫却不为所动』的领域有着深刻的研究
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
最佳答案

1.
file
whereIn -2sql

  1. file
    批量插入 -1 sql

file
不知道

3年前 评论
qingdiao 3年前
MIsakas (楼主) 3年前
讨论数量: 9
leo

日订单量超过 10W 了吗?没到这个数就不需要关心是 15 个 SQL 还是 5 个 SQL

3年前 评论
MIsakas (楼主) 3年前
leo

日订单量超过 10W 了吗?没到这个数就不需要关心是 15 个 SQL 还是 5 个 SQL

3年前 评论
MIsakas (楼主) 3年前

1.
file
whereIn -2sql

  1. file
    批量插入 -1 sql

file
不知道

3年前 评论
qingdiao 3年前
MIsakas (楼主) 3年前

2-4 明显就有问题,先解决 :see_no_evil:

3年前 评论

file

这三条换成 whereIn 试试,然后 User 表那几个查询也合并下

3年前 评论
php炎黄

Auth::id()会查询一次的,所以你不用在查一次的,试试Auth::user(),就可以获取到用户信息了

3年前 评论
MIsakas (楼主) 3年前

没有N+1就没有问题。

3年前 评论

最后你也没必要查订单吧,订单不是就在前面生成出来的吗?里面到底是插入的什么数据,不早就知道了

3年前 评论

我这两天可能疯魔了,满脑子都是redis,所以我的想法是把大部分查询都拿redis来做,mysql只做最后的入库操作.....

3年前 评论

api-token, 存redis

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!