我想知道你们是否可以帮助解决 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/