My goal is to only execute a SQL Insert if the same value not exists.
this is my table1:
id(auto_increment)
version(string)
My Query looks like this:
INSERT IGNORE INTO table1 (version) VALUES ('12345');
The problem is that the ignore statement not work because every row is different because of the id column (auto_increment).
Anybody here have a Solution to avoid double saving the same values?
Solution:
INSERT INTO table1 (version)
SELECT * FROM (SELECT '12345') AS tmp
WHERE NOT EXISTS (
SELECT version FROM table1 WHERE version = '12345'
) LIMIT 1;
Your issue has nothing to do with the auto-incremented column.
You need a unique constraint/index on version:
alter table table1 constraint unq_table1_version unique (version);
I also don't recommend insert ignore for this purpose. It might ignore other errors. Instead, use on duplicate key update:
insert into table1 (version)
values ('12345')
on duplicate key update version = values(version); -- this is a no-op
Related
So I'm trying to write an sql query to be execute from php to count number of downloads of a files. I have a table id,name,count and I want it to check if the name exists and increment count else to insert a new row.
I was trying to use if exists but that didn't work so now I'm trying to use the on duplicate key update statement. I inserted a row with the name lemons as a test case. I keep getting the error with my syntax near the WHERE statement. Am I approaching this right?
INSERT INTO `table` (`name`, `count`)
VALUES ('lemons',1) ON DUPLICATE KEY
UPDATE `count` = `count`+1
WHERE `name` = 'lemons';
i hava a table with varchar primary key, that is a foreing key for some other tables.
Something like:
ID-------------NAME
1011001020-----product 1
1011001022-----product 2
1011001025-----product 3
Then, i have this array
array(
'1011001020',
'1011001022',
'1011001025',
'x',
'y'
)
This array will be used to insert values in another table with FK, so if any value is not an ID on the first table, the INSERT query will brake.
How do i find 'x' and 'y' before any attempt to insert. I would like to avoid selecting all ids from table one and make a PHP comparison, since there are a lot of records. I would rather a MySQL approach
I would suggest the following procedure:
Create the table and insert all the values into the table.
Remove the values that do not match.
Add the foreign key constraint.
The second and third steps can be done easily in SQL:
delete from temporarytable
where tt.otherid not in (select ot.otherid from othertable ot);
alter table temporarytable
add constraint fk_othertable foreign key (otherid) references othertable(otherid);
You can load the data however you like. For speed, I would recommend load data infile.
give this a shot. Tested on server, products is the new table and inserted only rows found in the array from items table.
INSERT INTO `products` ( `name` )
SELECT `name` FROM `items` WHERE `vendor_id` IN ( 1,2,3,4,.... )
I am trying to find a method for inserting the last primary key from Table1 as a foreign key into Table2.
So far, I have tried SELECT max(‘id‘) FROM table1 as foreign_key blablablablablabla
It works if one user registers at that current time; however, if 5 users register at the same time, the foreign key is wrong.
Multiple ways you can do this.
Creating a trigger
You can create a trigger after insert of table1 into table2. For example;
CREATE TRIGGER `add to other table` AFTER INSERT ON `table1`
FOR EACH ROW INSERT INTO table2 SET user_id=NEW.id, name=NEW.username;
Using PHP
You can do this using mysqli::insert_id, for example; (You would bind and sanitize input, but for the sake of illustration, I won't)
$mysql->query("INSERT INTO `table1` SET `username`='pokrenz'");
$intForeignKey = $mysql->insert_id;
$mysql->query("INSERT INTO `table2` SET `id` = ". $intForeignKey);
I have a following
Table1 : userid, who, share, date :: id is auto increment and primary key
I would like to build a query to check if record exist and insert new record if is empty.
How to build this in a single query and insert multiple records using a single query
data to inser ('a1','a2','a3','a4'), ('b1','b2','b3','b4'), ('c1','c2','c3','c4'), .......
Create UNIQUE index on column that you want to be unique
Use INSERT IGNORE to insert unique data and ignore not unique
You could use REPLACE statemement that works just like INSERT only it doesn't do anything if the row already exists:
REPLACE INTO table ...
http://dev.mysql.com/doc/refman/5.0/en/replace.html
You should take careful look at mysql INSERT INTO documentation.
How to insert "on no exists" is simple. Let's say you want combination of user,who,share to be unique and use latest date. Update your table and create UNIQUE KEY on those fields:
ALTER TABLE Table1 ADD UNIQUE KEY (user, who, share);
Normally inserting the same combination would cause error but using INSERT IGNORE (link above) would silently ignore error:
INSERT IGNORE INTO Table1 (user,who,share,date) VALUES ( 1, 2, 3, NOW());
You may also force key to update on insert:
INSERT IGNORE INTO Table1 (user,who,share,date) VALUES ( 1, 2, 3, NOW())
ON DUPLICATE KEY UPDATE date = VALUES(date);
And inserting multiple values at once, again the first link:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
How do I double or triple the rows (duplication also fine) in an existing table using mysql?
This should do the trick, if you have no PRIMARY KEY or UNIQUE indexes.
INSERT INTO table SELECT * FROM table;
If you do have such indexes, simply list all the columns in the table that do not have these indexes. E.g. if colA has a UNIQUE or PRIMARY KEY index:
INSERT INTO table (colB, colC) SELECT colB, colC FROM table;
Note that this will only work if your ID column (colA) has the AUTO_INCREMENT property set (this is usually the case for integer ID columns). If not then you are out of luck. In that case you cannot use INSERT INTO ... SELECT to duplicate rows because you need to supply the unique indexes manually.
In words,
use select to get everything, than use insert....
You shouldn't do that.
Keep your tables in Normal form that means no duplicates.
INSERT INTO table (SELECT * FROM table)
You have to exclude the primary key.
INSERT INTO table (col1, col2) SELECT col1, col2 FROM table;
Do not select primary key.
You have to mention all the fields excluding primary key. I believe you have an auto-increment column do not mention that column in above command but include all other columns.
I agree with Col. Shrapnel: you should not do this.
Sander got it right:
if you want to do this, INSERT INTO
table SELECT * FROM table is the way
to go
If there is a PRIMARY AUTOINCREMENT key, insert into table (all-but-key) select all-but-key from table
If there are other UNIQUE keys, you can't do this.
Another dirty workaround:
SELECT * FROM TABLE UNION ALL SELECT * FROM TABLE
You could put this in a VIEW or a merge table...
An easy way to duplicate all rows in the same table:
INSERT INTO yourtable()
SELECT * FROM yourtable;
This ofc only works if you don't have any unique keys on the table.