views:

236

answers:

3

Hi, Let us consider a user table: Username,email1,email2

Now, I want to make sure that no two rows in this table have any common email address. What would be the best way to ensure this ?

E.g.: If table has row: "Bill,[email protected],[email protected]", then trying to insert a row like "Billy,[email protected],[email protected]" should give an error.

Thanks in advance, Chandresh

+1  A: 

Sadly, check constraints are not a feature of MySQL. Well, they are, but they're ignored.

Use a trigger, instead:

create trigger MyValidation after insert on user for each row
begin
    if (select count(*) from user where 
        email1 = new.email1
        or email1 = new.email2 
        or email2 = new.email1 
        or email2 = new.email2) > 0 then
        --I know that the delete could use this logic, but you can
        --insert other instructions here.

        delete from user where username = new.username

    end if
end
Eric
This is the correct answer to the question I have posed. But unfortunately my requirements have slightly changed and hence, I will use a separate table for email-user mapping.
A: 

Maybe you could use some sort of stored procedure, but this may be something that you could check for before inserting your data.

SELECT email1, email2 FROM yourTable 
WHERE email1 LIKE %@email% or email2 LIKE %@email%
Jason
+4  A: 

It looks like you're trying to force a combo between 1:1 and 1:multiple with your data model. Your better bet is to store each Username/Email combo separately. One row for "Username,email1" and another row for "Username,email2". If you have additional "Username"-related fields, those could stay in the core User table, while emails would move to a two-column Email table with a multi-column unique index on (Username,Email).

DreadPirateShawn
I just thought of the same answer when planning to look at this page for answers. The reason I choose this is 'username, email,bounced' ... so, you see I need a bounced flag as well and who knows what more later.
Oh yes, this also prevents the case of a user entering the same email for email1 and email2. :-)