How to write MySQL query to find foreign key entity exists? - mysql

I need to update the customer details in my table
If client_id exists in the client table and client_id exists in customer table I will update if not insert, using the following query
INSERT INTO `customer` (`username`, `password`, `client_id`)
VALUES ('username', 'password', 1)
ON DUPLICATE KEY UPDATE `password` = 'user-password';
I need to skip update and insert when client_id is empty(id not present in client table).
How to write MySQL query to skip this?

Try using REPLACE instead of INSERT. If the PRIMARY KEY exists, it would replace the row, but if not, then it would do the insert as usual.
REPLACE INTO `customer` (`username`, `password`, `client_id`)
VALUES ('username', 'password', 1);

Related

How to insert unique values without id

I would like to insert in my tables ROLES values if it does not exist yet, without using the id
My table ROLES (id, name)
Entries : 'admin', 'superadmin'
Could you please give me an example for MySQL?
I and to Insert the value in name only if this name is not already present in the table
ie. :
INSERT INTO ROLES (name) VALUES ('noadmin') should work
INSERT INTO ROLES (name) VALUES ('admin') should not work
Late info
CREATE TABLE IF NOT EXISTS roles (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8mb4;
The id column is optional if it is an autoincrement / primary key
INSERT IGNORE INTO `roles` VALUES ('admin');
INSERT IGNORE INTO `roles` VALUES ('superadmin');
or
INSERT IGNORE INTO `roles` VALUES ('admin'), ('superadmin');
The INSERT IGNORE statement will cause MySQL to do nothing when the insertion throws an error. If there’s no error, then a new row will be added to the table.
You should have a UNIQUE key constraint set on roles name column to prevent duplicates.

SQL INSERT if username doesn't exist

what is wrong with this query:
INSERT INTO `customers`(`username`, `password`)
VALUES (:username, :password)
WHERE NOT EXISTS (
SELECT `username` FROM `customers` WHERE `username`=:username
);
What's wrong with the query? It generates a syntax error.
If you want to prevent duplicates, then use a unique constraint on the table:
ALTER TABLE customers ADD CONSTRAINT unq_customers_username UNIQUE (username);
Then if you attempt to insert a duplicate value using
INSERT INTO `customers`(`username`, `password`)
VALUES (:username, :password);
You will get an error of a constraint violation.
Often in this case, you want to actually update the password in the existing row. You can do that using the MySQL extension ON DUPLICATE KEY UPDATE:
INSERT INTO `customers`(`username`, `password`)
VALUES (:username, :password)
ON DUPLICATE KEY UPDATE password = :password;

My sql prevent duplicate inserts in lookup table

I have a mysql script where I insert values to a type_table. If I execute this script again duplicate values will be inserted in type_table. I don't want to delete the type_table and re-insert because the id is foreign key for many other tables. How do I execute Insert statement only once assuming this script will be executed many times. It's kind of a lookup table that you populate only once in the beginning.
CREATE TABLE IF NOT EXISTS `type_table` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`type_text` VARCHAR(200),
`create_time` DATETIME NOT NULL,
PRIMARY KEY (`id`),
INDEX (`id`)
);
INSERT INTO `type_table` (`create_time`,`type_text`) VALUES
(now(), 'type1' ),
(now(), 'type2' );
you can set 'type_text' as a unique column in database to simply not allowing duplicate values

ON DUPLICATE KEY unrecognized in phpmyadmin

I have a mysql database hosted on a remote server, I'm using InnoDB. Everything else works fine but on phpmyadmin whenever I try to execute the following query
INSERT INTO User (user_id, location) VALUES (1, 'London') ON DUPLICATE KEY UPDATE location=VALUES('London')
It highlights ON, DUPLICATE, KEY because they're unrecognized keywords
Help please!
Please remove the VALUES(...) in your ON DUPLICATE KEY part.
INSERT INTO User (user_id, location) VALUES (1, 'London') ON DUPLICATE KEY UPDATE location = 'London'
If you want to update more than one column, you should use normal UPDATE syntax:
INSERT INTO User (firstColumn, secondColumn) VALUES (1, 'London') ON DUPLICATE KEY UPDATE firstColumn = 'ABC', secondColumn = 'DEF';
Before using ON DUPLICATE KEY you should add index for one or multiple column. You can use following command for adding new index.
ALTER TABLE `table_name` ADD UNIQUE `unique_index`(`column1`);
For multiple column index use following command.
ALTER TABLE `table_name` ADD UNIQUE `unique_index`(`column1`, `column2`);
Now you can INSERT/UPDATE one or more row together.
For inserting single row use following command.
INSERT INTO `table_name` (`column1`,`column2`,`column3`,`column4`) VALUES('value1','value2','value3','value4') ON DUPLICATE KEY UPDATE `column3`='value3', `column4`='value4';
OR
INSERT INTO `table_name` (`column1`,`column2`,`column3`,`column4`) VALUES('value1','value2','value3','value4') ON DUPLICATE KEY UPDATE `column3`=VALUES(`column3`), `column4`=VALUES(`column4`);
Using this command you can also INSERT/UPDATE multiple rows. Use following command for this purpose.
INSERT INTO `table_name` (`column1`,`column2`,`column3`,`column4`) VALUES('value11','value12','value13','value14'),('value21','value22','value23','value24') ON DUPLICATE KEY UPDATE `column3`=VALUES(`column3`), `column4`=VALUES(`column4`);

MySQL bulk insert (ignoring primary key id, but on duplicate update another key)

On a bulk insert, how do I ignore a duplicate key update for primary key 'id' while only updating the entry for another key 'another_unique_id'?
INSERT INTO
some_table (`id`, `another_unique_id`, `raw_data)
VALUES (5 , 'ABCDEFG', 'blah')
ON DUPLICATE KEY UPDATE ...?
For example -
If there's a record with id: 5, I don't want to update it. I'll just insert a new record.
If there's a record with 'ABCDEFG' in the 'another_unique_id' field, then I'd like to update that entry to 'blah'
I think you should pass
INSERT INTO
some_table (`id`, `another_unique_id`, `raw_data)
VALUES (NULL , 'ABCDEFG', 'blah')
ON DUPLICATE KEY UPDATE ...?
otherwise it doesn't make sense
At least on mysql you can use:
INSERT IGNORE INTO
some_table (`id`, `another_unique_id`, `raw_data`)
VALUES (5 , 'ABCDEFG', 'blah')
If a field with id 5 exists it will do the same as an update,
and if it doesn't exist, it will do the same as the regular insert.