How can I insert one into MySQL only if there is no field?
For example:
INSERT INTO persona (nombre, apellidos, edad) VALUES ('Nombre', 'Apellidos', 25)
WHERE NOT EXISTS (SELECT nombre FROM persona WHERE nombre = 'Daniel')
How can I insert one into MySQL only if there is no field?
For example:
INSERT INTO persona (nombre, apellidos, edad) VALUES ('Nombre', 'Apellidos', 25)
WHERE NOT EXISTS (SELECT nombre FROM persona WHERE nombre = 'Daniel')
what you should do in this case an SP. (stored procedure)
where you verify
CREATE PROCEDURE InsertIfNoExist
AS
IF NOT EXISTS ( SELECT nombre FROM persona WHERE nombre = 'Daniel' )
BEGIN
INSERT INTO persona (nombre, apellidos, edad) VALUES ('Nombre', 'Apellidos', 25)
END
Only declare the parameters to be inserted and the parameters the properties of your person object. when you are going to implement it, check the structure of an SP I hope I have helped you.
It depends on what? is what you want to verify if it exists. Judging from your sql query, I understand that you want the new record inserted, only if the name does not exist in the database. The problem of the query that you place, has syntax problems and also does not consider the "surname" field at any time. But I suggest 1 of 2 possible solutions: you can create a "unique" index by adding the "first and last name" fields that way Mysql does not allow records to be inserted when you try to register a similar name and surname, throwing a duplicate entry error. you can create the table like this:
CREATE TABLE 'persona' (
'nombres' VARCHAR(100) NULL,
'apellidos' VARCHAR(100) NULL,
'edad' VARCHAR(100) NULL,
UNIQUE INDEX 'nombres_sin_repetir' ('nombres', 'apellidos'))COLLATE='utf8_general_ci';
The server will throw an error if you try to register something that already exists, then modify the insert query to avoid this, indicating in advance that if a repeated value arrives, update the value for example:
INSERT INTO persona (nombres, apellidos, edad) VALUES ('valor','valor',15) ON DUPLICATE KEY UPDATE nombres = nombres, apellidos = apellidos;
Or do an INSERT IGNORE
INSERT IGNORE INTO persona (nombres, apellidos, edad) VALUES ('valor','valor',15);
I hope it serves you, and if it is not what you are looking for, you tell us to give you a solution