MySQL: how to insert multiple entries but skip the existing ones? - mysql

I am trying to insert multiple entries into a table. However, some of these entries may be the same to existing ones: in such scenarios, these duplicate entries should not be inserted.
Here's an example:
table
id name number
1 alice 12345
2 bob 67890
id is auto-increment, while name and number are actual data.
Say now I have 3 more entries that I want to insert in the table using one instruction:
name number
alice 12345
alice 54321
bob 67890
Since the 1st and 3rd record is already there in the table, it would be desired to ignore them in insertion. But the db will take id as a key also, which is always different for each entries. So how may I subvert this, please?
Thanks!

If the unique key is supposed to be (name, number), then put a unique index on it. If you want to skip duplicate entries, check out INSERT...IGNORE or do some serious magic with ON DUPLICATE KEY.

Related

SQL - Make sure a column is unique over multiple rows?

I have a table in MySQL, which represents a user, that should be able to add up to three phone numbers to his account. So of course no phone number, that already exists should be able to be registered again. I made all three columns unique, but the problem is, that you can still enter as number 2 a number, that someone else entered as his first number. So I was wondering, if there is an SQL possibility to ensure, that one row is unique with other rows too or I need to solve this issue with querying, if there exists already a member with this number programmatically.
MemberID
Main number
Number 2
Number 3
1
123
456
789
2
456
123
567
So this example should be forbidden.
So as Strawberry assumed the best solution is to normalize the table. Since every member as 1 to n numbers, the numbers should be an own entity.
The resulting solution would be to remove the number fields out of the member table and create a new table, which looks the following:
Member_Id (Foreign Key)
Priority
Number
1
1
234
...
...
...
Then a unique constraint on the number column ensures, that no number is used by two members.

Syncronizing entries in a table according to a user array in MySQL

I have the following situation. The entries in a table come from a list of users for a particular id. That way id 7 has 3 rows for, say, 2, 6, 7 (these three are unique ids for a user data table). To clarify the table looks like this.
ID USERID KEYID
Where KeyID is auto_inc and is the table's primary key.
These entries come from a multiple select field. So a user might want to delete user 2 and add user 8. So the function that needs to update the table gets the array 8,6,7 for id 7. The quick way I found to do the syncronization is simply to delete every entry in the table for ID 7 and add 3 new entries of the from (ID,USERID) (7,8) (7,6) (7,7).
However I don't know if this is how it's supposed to be. Is there a better way? Also this methods drives the keyid up really fast (for every modification in the table, basically). Is that a problem? I'm an newbie with these things, so please be patient.
Well, you can delete rows selectively like this:
DELETE FROM my_table WHERE user1 = 7 AND user2 NOT IN (8,6,7)
where (8,6,7) is list of pairs (7,6),(7,8),(7,7) , that should be preserved, kept, not deleted, and it will delete all other pairs (7,?)
Your next question may be "Then how to add pairs while not making duplicities?"
You will first need to teach your table what duplicity is. By adding unique key on pair of fields (user1,user2). That would forbid duplicities. Now, when inserting new rows that may be already there, use "INSERT IGNORE" to ignore such exception and simply, continue on.

many to many relationship bridge table dilemma

salesman
========
uId
salesGroupLinked
================
uId
groupId
//add performacesScore field here
group
======
groupId
I have 3 table above that formed many to many relationship, and I would add a field 'performaces' (INT) so that each salesman can have a score in each group. And I believe it should be located at salesGroupLinked table. But since uId and groupId is FK, I can't insert / edit the data (I'm using phpmyadmin). I can't make the performacesScore field unique since they can be same value for example a salesman get 10 and another get the same.
I got this msg :
This table does not contain a unique column. Grid edit, checkbox,
Edit, Copy and Delete features are not available.
describe salesGroupLinked
The tool is simply telling you that there can be several entries for a uId-groupId combination. Example:
uId groupId performacesScore
1 1 10
1 2 20
2 1 30
2 1 30
2 1 40
2 2 20
Now imagine this data is shown to you and you make the first 2/1/30 a 2/1/50. What update statement could the tool sent to the dbms?
update salesGroupLinked set performacesScore = 50
where uId = 2 and groupId = 1;
This would update three records instead of one.
update salesGroupLinked set performacesScore = 50
where uId = 2 and groupId = 1 and performacesScore = 30;
This would still update two records instead of one.
So in order to properly update and delete, you must tell the dbms what makes the records unique. There are four possibilities:
If you never want to update or delete single records, leave it as is.
If you want to be able to update and there can only be one entry for a uId-groupId combination, then tell the dbms so and make uId plus groupId the primary key of your table.
If you want to be able to update and there can be duplicates for a a uId-groupId combination, but a uId-groupId-performacesScore combination will always be unique, then make these three the table's primary key.
If you want to be able to update and there can be duplicates for any combination, then give the table another column for a technical id and make this the primary key.

How can I change auto increment primary key values on row deletion?

I have a problem that whenever I delete a row, the row ID corresponding to that row gets deleted, but I don't want this. What I want is if any row is deleted, then other rows after that row should shift one (the no. of rows deleted) position up.
Example:
Suppose there is a user table(id and name)
id(auto incremented primary key) name
1 xyz
2 aaa
3 ray
4 mark
5 allen
now delete row with id=3 and table should look like
id(auto incremented primary key) name
1 xyz
2 aaa
3 mark
4 allen
Is there any way to accomplish this?
No! Don't do this!
Your Autoincrement ID is the IDENTITY of a row. Other tables use this ID to refer to a certain row. If you update the ID, you would have to update all other tables referencing this row, which is not at all the point of a relational database.
Furthermore, there never is a need to do this: you won't run out of autoincrement columns fast (and if you do, just pick a bigger datatype).
An autoincrement ID is a purely technical number, your application users should never see or use it. If you want to display an identificator to your users, add another column!
You've completely got the wrong end of the stick. Auto numbers should not be changed as this would break the link between any other referencing tables.
What you want, by the sounds of it, is a row counter, not a primary key.
While its generally not recommended to change these values, there do exists instances where you may need to change them. If you have the appropriate Foreign Key relationships setup to cascade on UPDATE then you could do this. Granted you need to be 100% all FK relationships are defined as expected.

How to handle fragmentation of auto_increment ID column in MySQL

I have a table with an auto_increment field and sometimes rows get deleted so auto_increment leaves gaps. Is there any way to avoid this or if not, at the very least, how to write an SQL query that:
Alters the auto_increment value to be the max(current value) + 1
Return the new auto_increment value?
I know how to write part 1 and 2 but can I put them in the same query?
If that is not possible:
How do I "select" (return) the auto_increment value or auto_increment value + 1?
Renumbering will cause confusion. Existing reports will refer to record 99, and yet if the system renumbers it may renumber that record to 98, now all reports (and populated UIs) are wrong. Once you allocate a unique ID it's got to stay fixed.
Using ID fields for anything other than simple unique numbering is going to be problematic. Having a requirement for "no gaps" is simply inconsistent with the requirement to be able to delete. Perhaps you could mark records as deleted rather than delete them. Then there are truly no gaps. Say you are producing numbered invoices: you would have a zero value cancelled invoice with that number rather than delete it.
There is a way to manually insert the id even in an autoinc table. All you would have to do is identify the missing id.
However, don't do this. It can be very dangerous if your database is relational. It is possible that the deleted id was used elsewhere. When removed, it would not present much of an issue, perhaps it would orphan a record. If replaced, it would present a huge issue because the wrong relation would be present.
Consider that I have a table of cars and a table of people
car
carid
ownerid
name
person
personid
name
And that there is some simple data
car
1 1 Van
2 1 Truck
3 2 Car
4 3 Ferrari
5 4 Pinto
person
1 Mike
2 Joe
3 John
4 Steve
and now I delete person John.
person
1 Mike
2 Joe
4 Steve
If I added a new person, Jim, into the table, and he got an id which filled the gap, then he would end up getting id 3
1 Mike
2 Joe
3 Jim
4 Steve
and by relation, would be the owner of the Ferrari.
I generally agree with the wise people on this page (and duplicate questions) advising against reusing auto-incremented id's. It is good advice, but I don't think it's up to us to decide the rights or wrongs of asking the question, let's assume the developer knows what they want to do and why.
The answer is, as mentioned by Travis J, you can reuse an auto-increment id by including the id column in an insert statement and assigning the specific value you want.
Here is a point to put a spanner in the works: MySQL itself (at least 5.6 InnoDB) will reuse an auto-increment ID in the following circumstance:
delete any number rows with the highest auto-increment id
Stop and start MySQL
insert a new row
The inserted row will have an id calculated as max(id)+1, it does not continue from the id that was deleted.
As djna said in her/his answer, it's not a good practice to alter database tables in such a way, also there is no need to that if you have been choosing the right scheme and data types. By the way according to part od your question:
I have a table with an auto_increment field and sometimes rows get deleted so auto_increment leaves gaps. Is there any way to avoid this?
If your table has too many gaps in its auto-increment column, probably as a result of so many test INSERT queries
And if you want to prevent overwhelming id values by removing the gaps
And also if the id column is just a counter and has no relation to any other column in your database
, this may be the thing you ( or any other person looking for such a thing ) are looking for:
SOLUTION
remove the original id column
add it again using auto_increment on
But if you just want to reset the auto_increment to the first available value:
ALTER TABLE `table_name` AUTO_INCREMENT=1
not sure if this will help, but in sql server you can reseed the identity fields. It seems there's an ALTER TABLE statement in mySql to acheive this. Eg to set the id to continue at 59446.
ALTER TABLE table_name AUTO_INCREMENT = 59446;
I'm thinking you should be able to combine a query to get the largest value of auto_increment field, and then use the alter table to update as needed.