MySQL – Update Based on SELECT Result

MySQLsubqueryupdate

Here are two SQL statements. One is an update statement and the other is a select statement. I want to combine them.

Update

update customer_entity 
set website_id = 4 
where website_id = 3

Select

SELECT count(*) c, email 
FROM `customer_entity` 
where website_id in (3,4) 
group by email 
having c <= 1) e

I tried:

update customer_entity 
set website_id = 4 
where website_id = 3 
where email in 
(
    SELECT count(*) c, email 
    FROM `customer_entity` 
    where website_id in (3,4) 
    group by email 
    having c <= 1
) e) 

I want to update the website_id according to the select statement. I tried to implement it but not successful, does anyone know how to do that?

Best Answer

update customer_entity 
set website_id = 4             
where website_id = 3 
AND email in 
(
    select tt.email 
    from 
    (
        SELECT email 
        FROM `customer_entity` 
        where website_id in (3,4)
        group by email 
        having count(email) <= 1
    ) as tt
)