Database requires duplicate values as primary key ( Which is not allowed )? - mysql

I have a database assignment where I must build the following database.
The issue is, I am given a table to create called dependent which has 5 columns. 1 of these columns is dependent_name. It can't be a Foreign Key because there is not table for the dependents, so I assume it is suppose to be a Primary Key.
When I attempted to add the data in the table I was given an error that says I cannot have duplicate values for primary key.
Of course this is because you cannot have duplicate primary keys ( Alice is a duplicate value in this situation ), but I am not sure how to get around this. I guess I could make another table called dependent_info and make the dependent_name and FK, but this is not stated in the instructions from the teacher.
Is there something I am missing here?

Related

multiple primary key defined [duplicate]

Here is a gross oversimplification of an intense setup I am working with. table_1 and table_2 both have auto-increment surrogate primary keys as the ID. info is a table that contains information about both table_1 and table_2.
table_1 (id, field)
table_2 (id, field, field)
info ( ???, field)
I am trying to decided if I should make the primary key of info a composite of the IDs from table_1 and table_2. If I were to do this, which of these makes most sense?
( in this example I am combining ID 11209 with ID 437 )
INT(9) 11209437 (i can imagine why this is bad)
VARCHAR (10) 11209-437
DECIMAL (10,4) 11209.437
Or something else?
Would this be fine to use this as the Primary Key on a MYSQL MYISAM DB?
I would use a composite (multi-column) key.
CREATE TABLE INFO (
t1ID INT,
t2ID INT,
PRIMARY KEY (t1ID, t2ID)
)
This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.
I would not make the primary key of the "info" table a composite of the two values from other tables.
Others can articulate the reasons better, but it feels wrong to have a column that is really made up of two pieces of information. What if you want to sort on the ID from the second table for some reason? What if you want to count the number of times a value from either table is present?
I would always keep these as two distinct columns. You could use a two-column primay key in mysql ...PRIMARY KEY(id_a, id_b)... but I prefer using a two-column unique index, and having an auto-increment primary key field.
the syntax is CONSTRAINT constraint_name PRIMARY KEY(col1,col2,col3) for example ::
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
the above example will work if you are writting it while you are creating the table for example ::
CREATE TABLE person (
P_Id int ,
............,
............,
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
);
to add this constraint to an existing table you need to follow the following syntax
ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (P_Id,LastName)
Suppose you have already created a table now you can use this query to make composite primary key
alter table employee add primary key(emp_id,emp_name);
Aside from personal design preferences, there are cases where one wants to make use of composite primary keys. Tables may have two or more fields that provide a unique combination, and not necessarily by way of foreign keys.
As an example, each US state has a set of unique Congressional districts. While many states may individually have a CD-5, there will never be more than one CD-5 in any of the 50 states, and vice versa. Therefore, creating an autonumber field for Massachusetts CD-5 would be redundant.
If the database drives a dynamic web page, writing code to query on a two-field combination could be much simpler than extracting/resubmitting an autonumbered key.
So while I'm not answering the original question, I certainly appreciate Adam's direct answer.
Composite primary keys are what you want where you want to create a many to many relationship with a fact table. For example, you might have a holiday rental package that includes a number of properties in it. On the other hand, the property could also be available as a part of a number of rental packages, either on its own or with other properties. In this scenario, you establish the relationship between the property and the rental package with a property/package fact table. The association between a property and a package will be unique, you will only ever join using property_id with the property table and/or package_id with the package table. Each relationship is unique and an auto_increment key is redundant as it won't feature in any other table. Hence defining the composite key is the answer.
CREATE TABLE `mom`.`sec_subsection` (
`idsec_sub` INT(11) NOT NULL ,
`idSubSections` INT(11) NOT NULL ,
PRIMARY KEY (`idsec_sub`, `idSubSections`)
);
#AlexCuse I wanted to add this as comment to your answer but gave up after making multiple failed attempt to add newlines in comments.
That said, t1ID is unique in table_1 but that doesn't makes it unique in INFO table as well.
For example:
Table_1 has:
Id Field
1 A
2 B
Table_2 has:
Id Field
1 X
2 Y
INFO then can have:
t1ID t2ID field
1 1 some
1 2 data
2 1 in-each
2 2 row
So in INFO table to uniquely identify a row you need both t1ID and t2ID

MYSQL table column contraint based upon another tables columns

This is my first post and I'm a mysql noob, so I apologize for this question's length.
BACKGROUND
I have a lookup table cctypevals, with a foreign field 'cctypeID', in mysql this would be:
CREATE TABLE `cctypevals` (
`cctypevalsKEY` integer NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`cctypeID` varchar(50) NOT NULL, FOREIGN KEY(cctypeID) REFERENCES cctype(cctypeID) ,
`value` varchar(50) )
cctypeID contains field names from user tables, eg 'taskSTATE', 'serviceTYPE', 'projectCAT' etc.
The value field contains the only allowed values for these user table fields.
Thus cctypevals acts like a 'multi' keyed lookup table, for example:
select value from cctypevals where cctypeID ='serviceTYPE'
might return HomeVisit, BackToBase etc
I know it would be easier to have one lookup table per field but this is what I have.
QUESTION
How do I constrain (in a sql create table or alter statement), tables with fields like task.taskSTATE, service.serviceTYPE etc so they can only accept values from cctypevals.value where cctypeID contains the appropriate field name ?
In create or alter table statement you cannot do that, since the check constraint would be able to such things, but mysql has not implemented the check constraint yet (mysql can parse a check constraint, but it will not work).
You can create before insert and update triggers that check the specific restrictions and raise an sql error message if the updated value does not meet the requirements.

Add another primary key to table in mysql

I want to add another primary key to a table in mysql.
I use phpmyadmin to communicate with mysql server.
When I click the primary icon for the desired field it gives me this error:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
Edited:
here's the query:
ALTER TABLE `files` DROP PRIMARY KEY ,ADD PRIMARY KEY ( `file_type` )
How can I do it?
As the name "primary" key says, there may be only one of that (ref: Highlander).
What you might want to try is a UNIQUE KEY, that acts just like a primary for most purpouses. Auto_increment doesn't seem to fulfill any purpouse if used a second time - what'ts the point of two fields carrying exactly the same information?
I believe in your case, what you need is a composite key. I do not know your table structure, but here is a general example taken from here,
CREATE TABLE track(
album CHAR(10),
disk INTEGER,
posn INTEGER,
song VARCHAR(255),
PRIMARY KEY (album, disk, posn)
)
In this case, there is a combination of 3 columns which avoid the duplicate records as you require. Please let me know if I have any mistakes in understanding your scenario.
The error message says it, I think:
the auto_increment column must be key.
So use this query first:
ALTER TABLE 'files' CHANGE 'id' 'id' INT( 10 ) UNSIGNED NOT NULL;
this will remove the auto_increment.
Also, I recommend the Uniqe key as suggested by other answer. I believe there should always (almost) be an Id column in each table.
We can Give Primary Key only once for a table. You can prefer UNIQUE KEY to prevent duplicate records
ALTER TABLE Persons
ADD UNIQUE (P_Id)
You can mark all the fields you want as primary keys, including the existing one. The system internally will drop the existing one and will set all you marked.

problem setting up primary keys in mysql database... help?

I have a table set up on a mysql database called "access" with three columns called:
rights_id, (PRIMARY KEY)
username,
name,
In the rights_id column the user can only input 3 different values ("1","2", or "3") 1 means resource, 2 means manager, and 3 means administrator. my problem occurs when there are more than one row with the same rights_id (ie: more than one administrator).It displays an error that tells me i can't have a duplicate entry for the PRIMARY KEY... i was wondering if there was a way to supress this error and allow me to do this? im using vb.net to interact with my MYSQL database running on a Windows 7 OS. Thanks!
rights_id is primary key. You can have only distinct values of primary keys in a table. So consider another primary key or do not use rights_id column this way. You should learn more about relational databases if you would like to use them.
In my opinion the best solution there is to add anothe column id which could be a primary key (you could also set multi-column primary key but this wouldn't fit your data in my opinion).
I'm not sure what "name" means in that table. If it's safe for me to ignore it . . .
If each username can have only one "rights_id", then the primary key should be username. If each username can have more than one "rights_id"--if user Catcall can have rights_id 1 and 2 at the same time--then your primary key should be the pair of columns (rights_id, username).
Since MySQL doesn't enforce CHECK constraints, you should have a separate table of rights id numbers, containing three rows.
create table rights_ids (
rights_id integer primary key
);
insert into rights_ids values (1);
insert into rights_ids values (2);
insert into rights_ids values (3);
Then you can set a foreign key constraint that will prevent any numbers besides those three from appearing in the table named "access". Something like
alter table access
add constraint foreign key (rights_id) references rights_ids (rights_id);
Create a compound PRIMARY KEY of rights_id and username (if usernames are unique that is).
No, you can't suppress that error. The issue is that rights_id is NOT your primary key.
The primary key must be able to uniquely identify a row in your table. If you can have more than 1 rights_id entry, then that is NOT able to fulfill the role of a primary key.
Read this wiki article about unique keys (a primary key is a specific type of unique key).
As Shef pointed out, you'll likely want to use a compound primary key of rights_id and username if that combination actually uniquely identifies a single row in the table.

How do I to keep the values of a column unique in MySQL?

I do file parsing in Perl and insert into a table in a MySQL database. For example, I have the following fields:
S.No ,PCID,USERNAME, TIME INFORMATION.
1 203 JANE 22:08 updation
2 203 JANE 22:09 deletion
3 203 JANE 22:10 insertion
In this table I wanted to have the PCID to be unique, USERNAME to be unique. S.No is unique, since I have set it to autonumbering and it's the primary key. Now my question is:
If I add PCID and USERNAME as composite primary key, I still find duplicates in the table. There is no change. The same o/p. What should be done to remove the duplicate? Should I code in Perl to check for duplicates before insertion?
Please guide and provide assistance. Thanks in advance.
You want the S.No to remain the primary key and PCID + USERNAME to be unique, so close to what Hammerite said:
ALTER TABLE MyTable
ADD PRIMARY KEY (`S.No`),
ADD UNIQUE KEY `PCID_USER_uk` (`PCID`, `USERNAME`);
I'm assuming that you want each column to be unique, rather than each composite key to be unique. Use a unique constraint on the columns that should be unique:
http://www.java2s.com/Code/SQL/Select-Clause/Altertableaddunique.htm
http://www.java2s.com/Code/SQL/Select-Clause/SettingaUniqueConstraint.htm
I'm not sure what happens if you add a unique constraint to MySQL on a column that doesn't have unique values already. You might have to perform manual cleanup before it will let you add the constraint.
You definitely shouldn't do this in Perl. Good data driven apps are about getting all of the logic of the app as close to the data model as possible. This one belongs database side.
ALTER TABLE MyTable DROP PRIMARY KEY
ALTER TABLE MyTable
ADD PRIMARY KEY (`S.No`),
ADD UNIQUE KEY `PCID_uk` (`PCID`),
ADD UNIQUE KEY `USERNAME_uk` (`USERNAME`)
If the file you're importing from contains duplicate values and you want the duplicate values to be discarded, use the IGNORE keyword. If you're using LOAD DATA INFILE then this is achieved using syntax like this:
LOAD DATA INFILE 'file_name' IGNORE INTO TABLE ...
See this documentation page.