简体   繁体   中英

Get Last Record From Store MYSQL Performance

I was wondering if you guys could help some trouble with a query in MYSQL. I have a sales table, a cashbox table and a store table, and I need to get the last sale of each store.

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;

//fixed typo //EXPLAIN

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    

I've tried different join orders and this is the one that runs faster, I was wondering if you could help me with the performance issue or if there's a better way to do it.

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;

Your sales join isn't working right

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM