i'm currently using a replace into statement, I have a unique field which will cause it to UPDATE rather than INSERT if it finds a duplicate...
Problem is if it finds a duplicate i can't get to update on a few columns, it just wipes the lot.
Is there a similar "one statement" method where I can just UPDATE what I want?
I've found merge into but don't undertsnad the first bit about merge into table using table
You're going to want to use the INSERT...ON DUPLICATE KEY UPDATE syntax.
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
Here's an example that will try to create a record with an id, birthday, and name. If a record with the id field exists, it will do the update specified. The table has lots of other fields like email address, zip code, etc. I want to leave those fields alone if I update. (REPLACE INTO would lose any of that data if I didn't include it in the REPLACE INTO statement.)
INSERT INTO user (userid,birthday,first_name,last_name)
VALUES (1234,'1980-03-07','Joe','Smith')
ON DUPLICATE KEY UPDATE
birthday = '1980-03-07',
first_name = 'Joe',
last_name = 'Smith';
Related
I added a new column to an already existing table, I just need to get data into this new column...I assume I can use a variant of the insert command, yet I do not know how to specify the column name and then how to order the values going into the new column.
Ok, after some conversation through the comments lets go to an answer.
I suppose your table is something like id, name, age, dateBirth, etc fields. But whoever create this table forget to add the gender for the registries. As you said that the new column is an sex enum('m', 'f') you will have to update every registry on this table one by one. Like this:
update matches set sex = 'm' where id = 1;
Pay attention that with this command I just updated the row on the table where the id=1 and Im assuming that id is your primary key. On the where caluse you have to put your primary key, otherwise you may update more then one column.
If your table has many registries there is a way that you can do it cuting down the heavy work (at least a little)
In order to update many rows at once you have to do an Update with a LIKE filter, you will set a filter that can identifie many womans at a time then many men at time as this:
update matches set sex = 'f' where name like '%Jheniffer%'
Since Jheniffer is a female name most likely you will update every registry which has part of the name as Jheniffer like 'Jheniffer Smith'. So repeat this process for the common names until the work is done. For all womens then repeat for the men.
Hope it help you to understand
you have to use update command, insert is for adding new rows.
update myTABLE set NewColumn = ?
Why INSERT here? You need to UPDATE data to column inserted.
Here is the list of steps
Alter the table then add column with constraint is NULLABLE.
Process the update the column added using UPDATE command.
If you want the column added is NOT nullable. Just re-alter the column and change it to NOT nullable.
You can use UPDATE command.
UPDATE my_table SET new_col='new_val'
if you need to set new column value just in few rows add WHERE clause
UPDATE my_table SET new_col='new_val' WHERE condition='true'
This question is somewhat about "best practices", but also a search for potential problems. I would like to be able to run an update on multiple fields and assign different values without running multiple queries and not using a super complex query. So, what I've done is created a table with a primary key and the "name" column as a unique key.
Now, when I want to update multiple columns with different values, I can run a query like this:
INSERT INTO my_table (name, description) VALUES ('name', 'mydescription'), ('name2', 'description2') ON DUPLICATE KEY UPDATE description = VALUES(description)
Is this a bad idea? Is there a better way to do this? Are the standards police going to come arrest me?
Edit: I did just notice one potential issue with this, being a race condition. If one user removes a row while another user is editing it and they save the information, the edit will recreate the row. (Which could be used as a feature or a bug.)
Further to my comment above (linking to a question where another poster advises of the performance impact from using INSERT ... ON DUPLICATE KEY UPDATE where the records are known to exist), one could use the multiple-table UPDATE syntax with a table materialised from constants using UNION:
UPDATE my_table JOIN (
SELECT 'name' AS name, 'mydescription' AS description
UNION ALL
SELECT 'name2', 'description2'
) t USING (name) SET my_table.description = t.description
I read about the MySQL command ON DUPLICATE KEY UPDATE. I have a column Surnames in a Users table. Since there must be no identical surnames, I want to INSERT a new surname when the surname isn't in the database, and leave the row as it was recorded if the surname was previously saved in the database, without updating it. How can I achieve this?
INSERT IGNORE ... will try to insert a new row, if a duplicate key is found the new data will be discarded.
Documentation of INSERT
Following on from this: SQL INSERT from SELECT and the correct answer marked there.
I will need to be able to also check whether the row already exists, also by using the username. So would I delete and then insert or is there a better way?
And if it is delete, how do I say DELETE FROM table WHERE UserID = do the username select here
Thanks
If delete then you can use:
DELETE a FROM Avatar a LEFT JOIN User u ON a.UserID=u.UserID WHERE u.UserName='theusername'
Try REPLACE INTO instead of INSERT INTO. If the UserID is specified and is the primary key for the table, this will overwrite the row whose UserID matches what you insert.
To answer your sub-question, it would be DELETE FROM table WHERE UserID IN (SELECT UserID ...)
Side note: StackOverflow is really not an appropriate venue for learning basic SQL. If you read up first, your questions will be better and the answers correspondingly more useful.
Coming from the other question where you're doing an "insert from select", I assume you want to not insert the row that already have entries for the keys you're attempting to insert. I also assume that it's giving you some error like "duplicate key found".
With those assumptions in mine, the fix is simple: add the IGNORE keyword after INSERT, so you're query looks something like this:
INSERT IGNORE... //rest of query
With MySQL, if I have a field, of say logins, how would I go about updating that field by 1 within a sql command?
I'm trying to create an INSERT query, that creates firstName, lastName and logins. However if the combination of firstName and lastName already exists, increment the logins by 1.
so the table might look like this..
firstName----|----lastName----|----logins
John Jones 1
Steve Smith 3
I'm after a command that when run, would either insert a new person (i.e. Tom Rogers) or increment logins if John Jones was the name used..
Updating an entry:
A simple increment should do the trick.
UPDATE mytable
SET logins = logins + 1
WHERE id = 12
Insert new row, or Update if already present:
If you would like to update a previously existing row, or insert it if it doesn't already exist, you can use the REPLACE syntax or the INSERT...ON DUPLICATE KEY UPDATE option (As Rob Van Dam demonstrated in his answer).
Inserting a new entry:
Or perhaps you're looking for something like INSERT...MAX(logins)+1? Essentially you'd run a query much like the following - perhaps a bit more complex depending on your specific needs:
INSERT into mytable (logins)
SELECT max(logins) + 1
FROM mytable
If you can safely make (firstName, lastName) the PRIMARY KEY or at least put a UNIQUE key on them, then you could do this:
INSERT INTO logins (firstName, lastName, logins) VALUES ('Steve', 'Smith', 1)
ON DUPLICATE KEY UPDATE logins = logins + 1;
If you can't do that, then you'd have to fetch whatever that primary key is first, so I don't think you could achieve what you want in one query.
This is more a footnote to a number of the answers above which suggest the use of ON DUPLICATE KEY UPDATE, BEWARE that this is NOT always replication safe, so if you ever plan on growing beyond a single server, you'll want to avoid this and use two queries, one to verify the existence, and then a second to either UPDATE when a row exists, or INSERT when it does not.
You didn't say what you're trying to do, but you hinted at it well enough in the comments to the other answer. I think you're probably looking for an auto increment column
create table logins (userid int auto_increment primary key,
username varchar(30), password varchar(30));
then no special code is needed on insert. Just
insert into logins (username, password) values ('user','pass');
The MySQL API has functions to tell you what userid was created when you execute this statement in client code.
I not expert in MySQL but you probably should look on triggers e.g. BEFORE INSERT.
In the trigger you can run select query on your original table and if it found something just update the row 'logins' instead of inserting new values.
But all this depends on version of MySQL you running.