SQL join:選擇一對多關係中的最後一條記錄 - SQL join: selecting the last records in a one-to-many relationship

問題:

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客戶: idname
  • purchase: id , customer_id , item_id , date購買: idcustomer_iditem_iddate

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章