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

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.

Related

Mysql - Multiple unique sets in a single Column based on another column value

I must create a table for handling student data which has two columns department code and register number,. For Eg. dept 101 has 30 students with register numbers (1-30) And dept 102 has 30 different students with same register numbers (1-30) . for instance.,The student with regno:3 who belongs to dept:101 and another student with regno:3 but in the dept:102 are in same table.,There can be same regno's but different dept code is there a way to relate my two columns.. I have added another image for more clarifications Table Structure with data My problem is how can i have unique set register numbers for each deparment in the same column to avoid duplication. The Values of reg_no with same Department Code must have a unique set,.. and another set of regno with a different dept_code must have another or individual set of unique set of numbers
Can i Have Multiple unique sets in a single Column..??
The
Table sample image
Is there any solution or should i use another table for each dept_code
Tried on Googling didn't Get a result yet . Thanks in Advance
try this
UNIQUE KEY 'thekey' ('dept','regno');
more about the background is found at this StackOverflow post

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.

Combine Access tables

Before you think this is a question that has already been answered, hear me out.
I inherited an Access MDB file. It has 2 tables (actually 4 but I'm only really concerned with 2). One is a member table with an AutoNumber field. The second table has the same fields but the ID field is simply Number (not AutoNumber). This second table gets the names of people when they "retire".
The problem now is some people want to return. I can't copy them back in because they will get a new ID number and all of the other report data (that I didn't mention before) is keyed to their original ID number which is still unique between the two tables.
What I think I'd like to do is temporaily turn off the AutoNumber field long enough to allow me to merge the data from the "retired" table, then turn AutoNumber back on. But Access won't let me do that because the AutoNumber ID is tied to other tables and various reports. (I guess I do care about the other tables.)
This answer is close, Adding records with old ids that were generated using auto number in access, but focuses on 1 row. I have plenty. Same with this answer: Keep value of autonumber column when importing into Microsoft Access database.
I'm thinking the second answer is really close, but I don't know how to use docmd.RunSQL.
If this is simple and I'm just missing the obvious, I'm willing to admit being a NOOB with Access.
Access will let you INSERT a row with a number for an autonumber field as long as the number you're inserting doesn't conflict with any of the existing values. And since "their original ID number which is still unique between the two tables", it sounds like that is your situation.
Consider these 2 tables:
tblMembers
id fname
1 Anne
3 Cathy
tblRetired
id fname
2 Bob
4 David
This INSERT statement (the Access query designer calls it an "append query") will add the tblRetired rows to tblMembers.
INSERT INTO tblMembers ( id, fname )
SELECT r.id, r.fname
FROM tblRetired AS r;
This is tblMembers after executing that INSERT ...
id fname
1 Anne
2 Bob
3 Cathy
4 David

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

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.

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.