0

I'm having problems with the next sentence:

INSERT INTO `pasajeros` 
( 
    `nombre`,
    `apellidos`,
    `email`,
    `password`,
    `telefono`
) 
VALUES 
(
    'Alexandra',
    'Gonzalez',
    'cesa@cesar3.com',
    '1234567!',
    '04242344556' 
) 
WHERE NOT EXISTS 
( 
    SELECT  * 
    FROM    `transportistas` 
    WHERE   `email` = 'cesa@cesar3.com'
);

What's wrong in my code? I need to make an Insert if a email is not used in another table. That was my approach, but I can't figure it out why my query fails.

Siyual
  • 16,415
  • 8
  • 44
  • 58
Cesar Jr Rodriguez
  • 1,691
  • 4
  • 22
  • 35

2 Answers2

3

I don't believe you can use Values with a where clause. But you can insert using a select statement which can handle a where clause just fine.

INSERT INTO `pasajeros` 
( 
    `nombre`,
    `apellidos`,
    `email`,
    `password`,
    `telefono`
) 
Select * from (
select 
     'Alexandra' as `nombre`,
     'Gonzalez' as `apellidos`,
     'cesa@cesar3.com' as `email`,
     '1234567!' as `password` ,
     '04242344556' as `telefono`
    ) i
WHERE NOT EXISTS 
( 
    SELECT  * 
    FROM    `transportistas` 
    WHERE   `email` = i.email
);
Brad
  • 11,934
  • 4
  • 45
  • 73
2

The correct way to do what you want is to define a unique index/constraint:

create unique index unq_pasajeros_email on pasajeros(email);

The database will then protect the data.

This is much better than trying to do this at the application layer, because it prevents duplication if someone manually updates the data.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • What means unq_pasajeros_email? The email must to be unique in both `pasajeros` and `transportistas` tables, the field in both cases is called `email` – Cesar Jr Rodriguez Mar 16 '17 at 20:20
  • @CesarJrRodriguez . . . Then you need two unique indexes, one for each table. However, your question only concerns `pasajeros`. – Gordon Linoff Mar 17 '17 at 02:04