insert if not exist without making column unique - mysql

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.

Related

inserting data into a new column of an already exsisting table

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'

Inserting Persons with IDs in one query?

I need to add data to a MySQL database like that:
Person:
pId, nameId, titleId, age
Name:
nameId, name
Title:
titleId, title
I don't want to have any names or title more then once in the db so I didn't see a solution with LAST_INSERT_ID()
My approach looks like that:
INSERT IGNORE INTO Name(name) VALUES ("Peter");
INSERT IGNORE INTO Title(title) VALUES ("Astronaut");
INSERT INTO Person(nameId, titleId, age) VALUES ((SELECT nameId FROM Name WHERE name = "Peter"), (SELECT nameId FROM Name WHERE name = "Astronaut"), 33);
But I guess that's a quite dirty approach!?
If possible I want to add multiple persons with one query and without having anything more then one times in db.
Is this possible in a nice way? Thanks!
You could put title and name as two columns of your table and then:
set one UNIQUE index on each column if you don"t want to have two titles or two names identical in the DB
or set an UNIQUE index on (title,name) if you don't want to have two entries having both the same name and the same title.
If you really want to have separate tables, you could do as you suggested in your post, but wrapping all your insert statements in a TRANSACTION to allow rollback if you detect a duplicate somewhere.
See Design dilemma: If e-mail address already used, send e-mail "e-mail address already registered", but can't because can't add duplicate to table which appear to be exactly the same problem, but having name & email instead of name & titles.
START TRANSACTION;
INSERT INTO title(value) VALUES ("Prof.");
SELECT LAST_INSERT_ID() INTO #title_id;
-- Instead of using user-defined variable,
-- you should be able to use the last_insert_id
-- equivalent from the host language MySQL driver.
INSERT INTO username(value) VALUES ("Sylvain");
SELECT LAST_INSERT_ID() INTO #username_id;
-- Instead of using user-defined variable,
-- you should be able to use the last_insert_id
-- equivalent from the host language MySQL driver.
INSERT INTO account(username_id, email_id) VALUES (#username_id,#title_id);
COMMIT;
See LAST_INSERT_ID()
A third solution would be to SELECT before doing you insert to see in the entry are already present. But personally I wouldn't push to the check-before-set approach at the very least, this will require an extra query which is mostly superfluous if you use correctly indexes.

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

SQL INSERT or UPDATE

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

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