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