SQL INSERT or UPDATE - mysql

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

Related

How to use "Insert Ignore Into" Mysql query

I have three tables :
user_details
user_badges
badges
I have a query where I use "insert ignore into" command to insert the badge id from badges and user id from user_details into user_badge.
$username=$_SESSION['username'];
$getlife="SELECT * FROM user_details WHERE username='$username'";
$getlifedb=mysqli_query($db, $getlife);
while ($row=mysqli_fetch_array($getlifedb)){
if($row['fullife'] == '1'){
$full="INSERT IGNORE INTO user_badge(user_id, badge_id)
SELECT u.user_id, b.badge_id
FROM user_details as u
CROSS JOIN badges as b
WHERE u.user_id='$id'
AND b.badge_id='8'";
mysqli_query($db, $full) or die(mysqli_error($db));
}
}
Below is the picture of user_badge table:
But every time I execute the command, the insert ignore doesnt work, but instead it just insert a field again. Can someone help me fix this issue.
INSERT IGNORE only works when a duplicating field in table is being set as UNIQUE. user_id in table user_badge is not set to UNIQUE, that's why it duplicates it.
If you need to have multiple badges for an user, but those are not supposed to be duplicated, you need to set the pair to be UNIQUE, -> UNIQUE(user_id,user_badge)
Without UNIQUE, INSERT IGNORE doesn't make any sense, as it doesn't throw any errors when inserting the same records.
From msql documentation "Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error."
I agree fully with #Flush Thunder. If you do not care having duplicate entries just use INSERT instead, but for what you´re writing this is not the case.
Apparently, your user must have a unique id, while may have several badges which is consistent with a unique user.

insert if not exist without making column unique

I am searching for the answer of this question by many days. There are some answers on stackoverflow and on ther sites which I really don't understand. Basically I need to insert only if cell value for particular column does not exist.
Ex: See below table, if their are some duplicate names present it's ok like 'sandy' and 'edward'. But for some names like 'wilson' I don't want to insert. I don't want to make name column unique at all.
Note : Please don't give any complicated answer or procedural queries, it should be easy to remember.
you should make another column/table to determine which name can't duplicate
Then, you select the name whether can be duplicate or not from that table and then insert based on result
You can make a checkbox at HTML FORM.
You fill form values
If that checkbox checked, then before inserting in database, it will will check if exists then no insertion. If not exists then insert.
If that checkbox is not checked, then insert blindly
try the following:
INSERT INTO info (id, name)
SELECT null, 'wilson' FROM any_other_table_name
WHERE NOT EXISTS (
SELECT name FROM info WHERE name = 'wilson'
) ;
It will not insert if multiple entry.

INSERT ON DUPLICATE KEY UPDATE as substitute for UPDATE

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

mysql replace into alternative

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';

Increment a database field by 1

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.