问题:
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