I have MySQL table and I need to make query INSERT ON DUPLICATE UPDATE. "id" is primary key, I dont need it for now.
I need to insert values "id2", "name", "city" into the table. If there is some row with the same values in "id2" and "name", then just update "city".
Please where am I wrong ?
$query = "INSERT INTO
`table`
(id2, name, city)
VALUES
( '$new_id2', '$new_name', '$new_city')
ON DUPLICATE KEY UPDATE
city='$new_city'
WHERE
`id2`='$new_id2' AND `name`='$new_name'
";
In order to use ON DUPLICATE KEY UPDATE you must create an index to enforce uniqueness across the two columns id2, name for MySQL to be able to detect duplication. This will create the index with an identifier called idx_uniq_id2_name
`
Before you attempt this, you must ensure that you do not already have more than one occurrence of the combination of id2, name anywhere in your table. You can verify that with:
-- Check for non-unique rows
SELECT id2, name FROM table GROUP BY id2, name HAVING COUNT(*) > 1
If that returns no rows, you can successfully create the multi-column index.
-- Create a multi-column unique index
ALTER TABLE `table` ADD UNIQUE INDEX `idx_uniq_id2_name` (`id2`, `name`);
After the index has been created, you must correct the syntax of your INSERT statement such that it has no WHERE clause (which is never allowed for an INSERT).
INSERT INTO `table`
(id2, name, city)
VALUES ('$id2', '$name', '$new_city')
ON DUPLICATE KEY UPDATE city = '$new_city';
Please be advised that your use of variables like $new_city in the SQL statement suggest you are not using prepare()/execute() with PDO or MySQLi in your code. I would recommend reviewing How can I prevent SQL injection in PHP for suggestions on how to improve the situation.
Related
I would like to do something like this (the updated value should be different than the inserted value):
"INSERT INTO notification_chat_counts (uid,group_id,count)
VALUES
(",$uid,",",$groupId,",1)
ON DUPLICATE KEY UPDATE
(count = count +1)"
Of course it is possible. Even the MySQL manual has example of inserting different value that the values which would got updated:
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;
For your example, the correct query syntax would be:
$query = "INSERT INTO notification_chat_counts (uid,group_id,count)
VALUES (",$uid,",",$groupId,",1)
ON DUPLICATE KEY UPDATE count=count+1"
However for this statement to work you must have an UNIQUE type index defined for this table, so that MySQL can decide if such row already exists in the table or not.
Also remember that inserting values into SQL query like this is dangerous and not recommended. You should use prepared statements for that.
Structure table:
id (int primary key)
name (varchar 100)
date(datetime)
For insert I use query:
INSERT INTO table (name, date) VALUES ('t1','$date');
For delete row I use query:
DELETE FROM table WHERE name = 't1';
I would like want how make 1 query: first insert, if row with it name already exist, than delete row, and insert again.
Tell me please how to make it?
Create a UNIQUE index over your name column:
ALTER TABLE `table` ADD UNIQUE (name);
If you genuinely want to "delete row and insert again", then you can use REPLACE instead of INSERT. As documented:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
Therefore, in your case:
REPLACE INTO `table` (name, date) VALUES ('t1','$date');
However, if instead of deleting the existing record and then inserting a new one you merely want to update the existing record, you can use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO `table` (name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE date = VALUES(date);
The most material difference is in the treatment of columns for which you do not provide explicit values (such as id in your example): REPLACE will result in the new record having the default value, whereas INSERT ... ON DUPLICATE KEY UPDATE will result in the old value being retained.
What you want to do is use MySQL's on duplicate update feature.
Can be used like this :
INSERT INTO table (name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE name=VALUES(name),dateVALUES(date);
Of course for that to happen a dupliate violation must occur.
insert into table (name, date) values('t1','$date') on duplicate key update name=values(name), date=values(date)
Are you looking for an update query?
Update will set a value on an already existing row.
UPDATE table SET date = '$newdate' WHERE name = 't1';
The best way to do this is using the mysql methods together with your query.
If you make the 'name' field unique:
id (int primary key)
name (varchar 100) NOT NULL UNIQUE
date(datetime)
And alter the query to:
INSERT INTO table
(name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE date = "$date"
Is there a way of removing record on duplicate key in MySQL?
Say we have a record in the database with the specific primary key and we try to add another one with the same key - ON DUPLICATE KEY UPDATE would simply update the record, but is there an option to remove record if already exists? It is for simple in/out functionality on click of a button.
It's a work-around, but it works:
Create a new column and call it do_delete, or whatever, making it a tiny-int. Then do On Duplicate Key Update do_delete = 1;
Depending on your MySQL version/connection, you can execute multiple queries in the same statement. However, if not, just run a separate query immediately afterwords. Either way, the next query would just be: Delete From [table] Where do_delete = 1;. This way, if its a new entry, it will not delete anything. If it was not a new entry, it will then mark it for deletion then you can delete it.
Use REPLACE INTO:
replace into some_table
select somecolumn from othertable
will either insert new data or if thr same data exist will delete the data and insert the new one
The nearest possible solution for the same is REPLACE statement. Here is the documentation for REPLACE.
A similar question was asked on MySQL Forums and the recommended(and only) answer was to use REPLACE.
to be more clear with mySql:
values can be from same table:
replace into table1 (column1,column2) select (val1,val2) from table1
or
values can be from another table:
replace into table1 (column1,column2) select (val1,val2) from table2
or
values can be from any table with condition:
replace into table1 (column1,column2) select (val1,val2) from table1 where <br>column3=val3 and column4=val4 ...
or
also remember values can be static with table name for namesake:
replace into table1 (column1,column2) select (123,"xyz") from table1
no error will be thrown even if the update results in duplicate entry, as it will be replaced.
(remember) only autoincrement value will be increased;
and
if you have column with data-type "TIMESTAMP" with "on update CURRENT_TIMESTAMP", it will have no effect;
Yes of course there is a solutions in MySQL for your problem.
If you want to delete or skip the new inserting record if there already a duplicate record exists in the key column of the table, you can use IGNORE like this:
insert ignore into mytbl(id,name) values(6,'ron'),(7,'son');
Here id column is primary key in the table mytbl. This will insert multiple values in the table by deleting or skipping the new duplicate records.
Hope this will fulfill your requirement.
INSERT INTO options (owner, name, value, modified)
SELECT owner, name, value, modified, #draft:=draft FROM
(
...
) `options`
ON DUPLICATE KEY UPDATE value=VALUES(value), modified=#draft
Above will error with column count doesn't match row count.
Is there a way I can SELECT a column into #draft without it being included as part of the inserts values but so it's usable in the DUPLICATE KEY UPDATE?
As stated in the manual:
In the values part of ON DUPLICATE KEY UPDATE, you can refer to columns in other tables, as long as you do not use GROUP BY in the SELECT part. One side effect is that you must qualify nonunique column names in the values part.
Therefore, you could do:
INSERT INTO options (owner, name, value, modified)
SELECT owner, name, value, modified FROM ( ... ) options2
ON DUPLICATE KEY UPDATE value=VALUES(value), modified=options2.draft
See it on sqlfiddle.
INSERT INTO table('name') VALUES("abc") IF NOT EXISTS name='abc'
If abc doesn't exist in the name column, then insert it. How can I write that query?
INSERT IGNORE INTO table(name) VALUES('abc')
This will ignore the value if it already exists. Like pjotr said, this will require name to be a unique index.
Source
Try:
insert into table('name')
select 'abc'
where not exists (select 1 from table where name='abc')
You may either use REPLACE (syntax, or, equivalent INSERT ON DUPLICATE KEY UPDATE). This is more appropriate if there's more columns and you want to update the others for the given key.
Or the IGNORE modifier (INSERT syntax) along with a unique index for the 'name' column. In that case, the insert will be ignored if it violates the unique index, but won't throw an error. That's more appropriate if you don't want to change any values and just keep the record if it already exists.
One way to do it is testing it with an IF:
IF (select count(*) from table where name = 'abc') = 0
THEN
INSERT INTO table('name') VALUES("abc")
I would enforce the column as UNIQUE and catch the exception on the code side, if you have a unicity constraint on that field. Otherwise I tend to agree with other answers.
I have Some Code...hope it will help you..
mysql_query("INSERT INTO authors (author) VALUES ('$rec_fic_author')
WHERE NOT EXISTS (SELECT * FROM authors WHERE author='$rec_fic_author')")
or die("cannot insert author");
here author is the name of table
authorID (pk)
author $rec_fic_author is _POST variable