简体   繁体   中英

How can I create a unique constraint 2 columns on Boolean Values?

I have a table which name is address_book.

I have fields id, user_id, ...... , default_address, address_type

address_type is boolean (0: Delivery Address - 1 : Invoice Address) default_address is boolean (0: Not Default Address - 1 : Default Address)

Think that a company has 8 address. Five addresses are for delivery, Three adresses are for invoice.

But in same time Only one default value depends on address_type. One default address for delivery one default address for invoice.

If i query this statement

alter table address_book add unique index(default_address, address_type)

it won't be logical.

id | user_id | default_address | address_type|
.. |   ..    |                 |             |
.. |   ..    |                 |             |
.. |   ..    |                 |             |
----------------------------------------------
12 |   10    |       1         |       1     |
----------------------------------------------
13 |   10    |       0         |       1     |
----------------------------------------------
14 |   10    |       0         |       1     |
----------------------------------------------
15 |   10    |       1         |       0     |
----------------------------------------------
16 |   10    |       0         |       0     |
----------------------------------------------
17 |   10    |       0         |       0     |

In this concept every user can maximum 2 default_address one is invoice one is delivery address.

How can i use unique index for that i want a validation for this situation.

How about adding two new tables, one for default invoice address and one for default delivery. Then you constraints on those two tables will just be address.id and user.id. With the primary key being both fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM