[英]Stored procedure to get default address among list of address for same user
My use case is to store multiple addresses for a customer, and to be able to designate a single customer's address as the customer's default address.我的用例是为一个客户存储多个地址,并能够将单个客户的地址指定为客户的默认地址。
I have three tables;我有三张桌子; customer
(contains customer details), address
(contains address details) and customer_address
(maps customers to their addresses). customer
(包含客户详细信息)、 address
(包含地址详细信息)和customer_address
(将客户映射到他们的地址)。 In customer_address
I have a field, is_default
, that, allows the address to be designated as the default address for one customer (using is_default
=1).在customer_address
我有一个字段is_default
,它允许将该地址指定为一个客户的默认地址(使用is_default
=1)。
Is it possible to write a stored procedure that returns the default address for a given customer?是否可以编写一个存储过程来返回给定客户的默认地址?
Assuming that you leave your database design as-is with the is_default
field in the customer_address
table, the query to return the default address might look something like below.假设您将数据库设计保留为customer_address
表中的is_default
字段,返回默认地址的查询可能如下所示。 It would be trivial to turn this query into a stored procedure (the only parameter needed would be the ID of the customer for whom you wish to return their defulat address):将此查询转换为存储过程很简单(唯一需要的参数是您希望为其返回其默认地址的客户的 ID):
SELECT a.*
FROM customer c
JOIN customer_address ca ON ca.customer_id = c.id
JOIN address a ON a.id = ca.address_id
WHERE ca.is_default = 1;
If you change your database design to store the default address ID in the customer
record, where perhaps it should be, the query is simplified:如果您更改数据库设计以将默认地址 ID 存储在customer
记录中(可能应该在该位置),则查询会被简化:
SELECT a.*
FROM customer c
JOIN address a ON a.id = c.default_address_id;
Of course, storing the default address in the customer record may make other aspects of your application more difficult, such as adding or removing addresses to/from a customer.当然,将默认地址存储在客户记录中可能会使应用程序的其他方面变得更加困难,例如向客户添加或从客户中删除地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.