简体   繁体   中英

MySQL + Updating rows based on value of one row

I have a few different sites that users can subscribe to my newsletters. Im using sendy for my newsletters and am having an issue with something. Sendy's db structure allows for the same email address to be in the db multiple times. Each email has its own id, unique id and list ID which is part of the problem.
When someone signs up from different sites they go to different lists.
If someone unsubscribes from one List ID, then that record gets an unsub value of '1'. I want to update all instances of their email address in the DB with a value of '0' (if they signed up from different sites) to all instances of their email to have '1'
I have looked at the following answers but can't seem to get my head wrapped around the answers properly.
mysql - UPDATEing row based on other rows
Updating rows based on other rows in the same table
This is part of the structure

Name    Type           Attributes   Null    Default Extra
id      int(11)        UNSIGNED     No      None    AUTO_INCREMENT
email   varchar(100)                Yes     NULL    
list    int(11)                     Yes     NULL    

This is an example of what Im looking for

id email          list unsubscribed
1  test@test.com  1    1
2  test@test.com  2    0
3  test@test.com  3    0

I need to determine that an email address has an unsubscribe value of '1' then all other occurences of that email address that has a '0' is updated to '1'
Should this be done in php or can I automate this in MySql?

Write a subquery that finds all the emails with unsubscribed = 1 . Join that with the original table to find all the other rows with the same email, and set them to 1 as well.

UPDATE YourTable AS t1
JOIN (SELECT DISTINCT email
      FROM YourTable
      WHERE unsubscribed = 1) AS t2
ON t1.email = t2.email
SET t1.unsubscribed = 1
WHERE t1.unsubscribed = 0

My guess would be (I didn't test this query, so be gentle):

$query = "UPDATE `tablename`
SET
    unsubscribed = 1
WHERE 
    email = (SELECT email from `tablename` WHERE id = " . $id . ")
";

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