php - 从存储中获取最后一条记录 MYSQL 性能

标签 php mysql sql

我想知道你们是否可以帮助解决 MYSQL 中的查询问题。 我有一个销售表、一个钱箱表和一个商店表,我需要获取每个商店的最后销售情况。

Sales
-----
#ID Sale //UNIQUE RANDOM IDENTIFIER NOT SEQUENTIAL
#FK Cashbox
Date
Amount

Cashbox
-------
#ID Cashbox
FK Store
Number

Store
-------
#ID Store
Name

SO basically in the sales table it is reported the amount the date and the cashbox in which the sale was made, I need to get as I said before the last sale from each store, the problem I'm facing is the query I'm running is too slow (around 6 secs) because (I think) the join with the sales table run through the whole table and it has 2 million+ records.

Here's the query I have:

SELECT st.name,MAX(s.date) as date
FROM store st
JOIN cashbox c ON c.id_store = st.id_store
JOIN sales s ON s.id_cashbox = c.id_cashbox AND c.id_store = st.id_store
GROUP BY st.id_store
ORDER BY date DESC;

//修正错别字 //解释

ID  select_type    table    type    possible_keys           key     key_len ref         rows    extra
1   SIMPLE      t   index   PRIMARY,id_store        PRIMARY     4   (null)          443 Using where; Using temporary; Using filesort
1   SIMPLE      c   ref FK_id_cashbox,FK_id_store   FK_id_tienda    4   pb.t.id_store       1   Using index
1   SIMPLE      v   ref id_cashbox          id_cashbox  4   pb.c.id_cashbox     2011    

我尝试了不同的联接顺序,这是运行速度更快的一个,我想知道您是否可以帮助我解决性能问题,或者是否有更好的方法。

最佳答案

SELECT st.name,MAX(s.date) as date
        FROM store st
        JOIN cashbox c ON c.id_store = st.id_store
        JOIN sales s ON c.id_cashbox = s.id_cashbox
        GROUP BY st.id_store
        ORDER BY date DESC;

您的销售加入无法正常工作

关于php - 从存储中获取最后一条记录 MYSQL 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20202433/

相关文章:

php - 代码点火器错误 "Unable to connect to your database server using the provided settings"

mysql - 无法使用 DELETE ON CASCADE 设置 FOREIGN KEY

gzip - mysqldump 管道 gzip 速度差异

php - SQL Join Ads with their Fields 将字段显示为列

MySQL - 内连接和分组依据

MySQL 存储过程变量

sql - 如何使用递归查询跟踪以前的 ID?

php - 在 Woocommerce 中将 Avada Catalog 排序 Hook 覆盖回默认值

javascript - 将php表转换成多个javascript文本框

php - 在循环中使用 ff mpeg 创建缩略图