Jump to content

Setting field to unique per user and not column


learningprobs

Recommended Posts

Hello,

 

I would like a little bit of guidance please to make sure I am not going to code something bad and have to redo it down the line.

 

I have these fields:

TAble = delivery_addresses
 
FIELDS = 
    user_id,
    company,
    name,
    surname,
    street,
    town_id,
    postcode,
    countries_id,
    primary
 
 
Each user has multiple delivery addresses but only 1 can be set as a primary = 1 at any one time.
My problem is how to set only 1 field to 1 but have all the others back to 0 per user.
 
With a bit of research I have this command(user = id of 170)

 

UPDATE delivery_addresses SET primary=IF(id=170, 1, 0)

 

From what I understood is that "if the user with the id of 170 is found, set the primary column to 1 and all the others to 0".

 

Am I correct to assume this?

 

 

 

Now if I wish to INSERT an address and set it as primary from the start, this will then require 2 queries, one insert that sets the primary to 0 and 1 to update it back to 1, is this the right way of doing it?

 

 

Thank you in advance.

 

 

 

 

  
Edited by learningprobs
Link to comment
Share on other sites

Ok, it seems that this works fine:

 

   UPDATE delivery_addresses SET
      primary_address = IF(address_id=5, 1, 0)
      WHERE user_id = 179
 
Could anyone confirm please that this is the right way to set 1 field to 1 while changing all the others to zero? Will this not cause a big load on the server when more and more rows are added?
 
Thanks,
Edited by learningprobs
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.