問題:
Suppose I have a table of customers and a table of purchases.假設我有一張顧客表和一張購買表。 Each purchase belongs to one customer.每次購買都屬於一個客戶。 I want to get a list of all customers along with their last purchase in one SELECT
statement.我想在一個SELECT
語句中獲取所有客戶的列表以及他們的最後一次購買。 What is the best practice?最佳做法是什麼? Any advice on building indexes?關於建立索引的任何建議?
Please use these table/column names in your answer:請在您的答案中使用這些表/列名稱:
- customer:
id
,name
客戶:id
,name
- purchase:
id
,customer_id
,item_id
,date
購買:id
,customer_id
,item_id
,date
And in more complicated situations, would it be (performance-wise) beneficial to denormalize the database by putting the last purchase into the customer table?在更復雜的情況下,通過將最後一次購買放入客戶表來對數據庫進行非規範化是否(性能方面)有益?
If the (purchase) id
is guaranteed to be sorted by date, can the statements be simplified by using something like LIMIT 1
?如果 (purchase) id
保證按日期排序,是否可以使用諸如LIMIT 1
類的東西來簡化語句?
解決方案:
參考一: https://en.stackoom.com/question/8rGa參考二: https://stackoom.com/question/8rGa