how to create a composite key in MySQL database - mysql

i am working on mysql server.where i have created a table, named question . column/attributes of this table are (course,subject,year,question)
i want to create a primary key(or composite key) consists of (course+subject+year). i.e. for a particular course+subject+year combination there can be only one question.there will be only one row with the combination of (course+subject+year),creation of another row won't be possible.
i have done it by :
primary key(course,subject,year);
but it's not working.still i can create two rows with same combination of course,subject,year.
can anyone tell me how can i create a composite key propery????

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)

if it is mysql you are looking at, you should do something similar to
ALTER TABLE table_name ADD PRIMARY KEY (a, b, c);

Related

Can there be a 1 to 1 relationship for keys with multiple fields?

I am creating web-app for database management. Database can be created using diagrams ER.
Here is screen from my app:
As you can see this pseudo example shows 4x types of cases:
1) Primary key --> Primary key (1:1)
2) Unique key --> Unique key (1:1)
3) Primary key consisting of two fields --> Primary key consisting of two fields (1:1)
4) Unique key consisting of two fields --> Unique key consisting of two fields (1:1)
And here is my question:
Is it all true? I wonder about these double keys... Is this really a 1 to 1 relation?
Generally, I wonder about these first 2 cases too. Are there also true?
MySQL Workbench shows it is not true:
I dont know why but you can see MySQL Workbench shows this is one to many relation...
Oracle Sql Developer:
Can anyone tell me when 1 to 1 relationship actually is?
Documentation shows i have right:
https://docs.oracle.com/cd/E26180_01/Platform.94/RepositoryGuide/html/s1204onetoonewithauxiliarytable01.html
but diagrams ER in MySQL Workbench and Sql Developer shows something different...
SQL code from that tables:
CREATE USER "Student" IDENTIFIED BY "null";
CREATE TABLE "Student".Table1 (
PK_FK NUMBER NOT NULL
);
CREATE TABLE "Student".Table2 (
PK NUMBER NOT NULL
);
CREATE TABLE "Student".Table3 (
PK NUMBER NOT NULL,
UK_FK NUMBER
);
CREATE TABLE "Student".Table4 (
PK NUMBER NOT NULL,
UK NUMBER
);
CREATE TABLE "Student".Table5 (
PK_1_FK NUMBER NOT NULL,
PK_2_FK NUMBER NOT NULL
);
CREATE TABLE "Student".Table6 (
PK_1 NUMBER NOT NULL,
PK_2 NUMBER NOT NULL
);
CREATE TABLE "Student".Table7 (
UK_1_FK NUMBER,
UK_2_FK NUMBER
);
CREATE TABLE "Student".Table8 (
UK_1 NUMBER,
UK_2 NUMBER
);
ALTER TABLE "Student".Table1 ADD CONSTRAINT Table1_PK PRIMARY KEY (PK_FK);
ALTER TABLE "Student".Table2 ADD CONSTRAINT Table2_PK PRIMARY KEY (PK);
ALTER TABLE "Student".Table3 ADD CONSTRAINT Table3_PK PRIMARY KEY (PK);
ALTER TABLE "Student".Table4 ADD CONSTRAINT Table4_PK PRIMARY KEY (PK);
ALTER TABLE "Student".Table5 ADD CONSTRAINT Table5_PK PRIMARY KEY (PK_1_FK, PK_2_FK);
ALTER TABLE "Student".Table6 ADD CONSTRAINT Table6_PK PRIMARY KEY (PK_1, PK_2);
ALTER TABLE "Student".Table3 ADD CONSTRAINT Table3_UK1 UNIQUE (UK_FK);
ALTER TABLE "Student".Table4 ADD CONSTRAINT Table4_UK2 UNIQUE (UK);
ALTER TABLE "Student".Table7 ADD CONSTRAINT Table7_UK3 UNIQUE (UK_1_FK, UK_2_FK);
ALTER TABLE "Student".Table8 ADD CONSTRAINT Table8_UK4 UNIQUE (UK_1, UK_2);
ALTER TABLE "Student".Table1 ADD CONSTRAINT Table1_FK1 FOREIGN KEY (PK_FK)
REFERENCES "Student".Table2 (PK);
ALTER TABLE "Student".Table3 ADD CONSTRAINT Table3_FK2 FOREIGN KEY (UK_FK)
REFERENCES "Student".Table4 (UK);
ALTER TABLE "Student".Table5 ADD CONSTRAINT Table5_FK3 FOREIGN KEY (PK_1_FK, PK_2_FK)
REFERENCES "Student".Table6 (PK_1, PK_2);
ALTER TABLE "Student".Table7 ADD CONSTRAINT Table7_FK4 FOREIGN KEY (UK_1_FK, UK_2_FK)
REFERENCES "Student".Table8 (UK_1, UK_2);
That's perfectly possible. Here's an example for PostgreSQL:
create table t1 (
a int not null,
b int not null,
constraint uq1 (a, b),
constraint fk1 foreign key (a, b) references t2 (a, b)
deferrable initially deferred
);
create table t2 (
a int not null,
b int not null,
constraint uq2 (a, b),
constraint fk2 foreign key (a, b) references t1 (a, b)
deferrable initially deferred
);
In this case t1 (a,b) is unique and references t2 (a, b) that is also unique. That's a 1:1 relationship using "composite keys".
Note: This example uses "circular references" that is a standard part of SQL, but is only implemented [to my knowledge] by PostgreSQL and Oracle. It won't run in MySQL.
A one-to-one relationship is still a master-detail relationship. One table is the owner of the identifier and the other table references it through a foreign key. This is the relationship show in the MySQL Workbench and SQL Developer pictures.
Documentation shows i have right:
You link to Oracle's documentation for ATG Repository, which is a specialist tool for representing data generically, but even there we can see from the SQL that USER_TBL is the primary table and "owns" the ID column and JOB_TBL is the auxiliary table and references the ID.
CREATE TABLE usr_tbl (
id VARCHAR(32) not null,
nam_col VARCHAR(32) null,
age_col INTEGER null,
primary key(id)
);
CREATE TABLE job_tbl (
id VARCHAR(32) not null references usr_tbl(id),
function VARCHAR(32) null,
title VARCHAR(32) null,
primary key(id)
In other words, we can have a USER without a JOB but we can't have a JOB without a USER. But a USER can have only one JOB and one JOB belongs only to ONE user.
Your diagram is wrong because it renders TABLE7 and TABLE8 as peers. But foreign keys don't work like that. One table defer to the other. When I look at your notation I can't see whether TABLE8 owns TABLE7 or TABLE7 owns TABLE8. Whereas, it's quite clear in the MySQL and Oracle diagrams. The purpose of a data model is to clarify the database design not obfuscate it.
Note, it is perfectly possible to define two tables which have foreign keys that reference each other's primary key. The trick is insert data into them. This requires deferring the foreign key constraints. I view deferred constraints as a red flag, a sign of a broken data model.

Drop just one column constraint from a composite primary key constraint

I have a Mysql table having the following structure:
As you can see there is a composite primary key constraint between the fields: word_id and preposition_id.
I want to remove the Primary Key constraint from word_id without touching the preposition_id field, and without losing data from the linked tables (Foreign Key tables). How can I do it?
Regards.
There is no syntax available to modify a constraint and drop only "a half" of the primary key.
You must drop the whole primary key, and then recreate it from scrach.
Just:
ALTER TABLE tablename DROP PRIMARY KEY;
and then:
ALTER TABLE tablename ADD PRIMARY KEY ( preposition_id );
You need first to drop all foreign keys thar reference the primary key in this table.
Data in tables will be preserved.

How to change primary key of table

I want to change primary key of table, initially it was id, now i want to change it to userid
smsusers(id,fname,lname,userid)
Here id is varchar type
adn userid is int type
for this i am trying following query
ALTER TABLE smsusers DROP PRIMARY KEY
which is showing this error
#1025 - Error on rename of '.\xrcwrn_sms\#sql-ae0_6f' to
'.\xrcwrn_sms\smsusers' (errno: 150)
id of smsusers is associated with many tables as foreign key.
How to change the primary key.
Here is an example:
ALTER TABLE `database`.`table`
DROP PRIMARY KEY,
ADD PRIMARY KEY (`userid`);
The message is telling you that you can't drop the primary key yet because it is referenced by one or more foreign keys. You need to identify and drop the foreign keys first, then drop the primary key.
ERROR NO:150 means Foreign key definition problem. I think that some other table has a foreign key constraint depending on this PK, so you need to drop that first and rebuild it later.
I tried this link. This is working properly.
My steps are
CREATE INDEX id_pk_unique ON smsusers (id)
ALTER TABLE parent DROP PRIMARY KEY;
ALTER TABLE parent ADD PRIMARY KEY (userid);

Adding a MySQL constraint that a field exists as primary key of the same table

I'm creating a table that has a basisId field as the primary key. There's also another field parentBasis which would be a reference to another tuple with that.basisId equal to this.parentBasis. What I want to do to is express this constraint while creating the table.
Something like: ADD CONSTRAINT CHECK EXISTS this.parentBasis AS somewhere.basisId (Obviously not real MySQL).
A quick browse through the MySQL dev pages didn't do much good. Any help would be appreciated.
Thanks.
If you're using InnoDB then you can create a foreign key from the table to itself. For example:
create table t (
id int not null primary key,
parent int null
);
alter table t add constraint foreign key (parent) references t(id);
then t.parent would either have to be NULL or a t.id value.

MySQL Removing Some Foreign keys

I have a table whose primary key is used in several other tables and has several foreign keys to other tables.
CREATE TABLE location (
locationID INT NOT NULL AUTO_INCREMENT PRIMARY KEY
...
) ENGINE = InnoDB;
CREATE TABLE assignment (
assignmentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
locationID INT NOT NULL,
FOREIGN KEY locationIDX (locationID) REFERENCES location (locationID)
...
) ENGINE = InnoDB;
CREATE TABLE assignmentStuff (
...
assignmentID INT NOT NULL,
FOREIGN KEY assignmentIDX (assignmentID) REFERENCES assignment (assignmentID)
) ENGINE = InnoDB;
The problem is that when I'm trying to drop one of the foreign key columns (ie locationIDX) it gives me an error.
"ERROR 1025 (HY000): Error on rename"
How can I drop the column in the assignment table above without getting this error?
As explained here, seems the foreign key constraint has to be dropped by constraint name and not the index name.
The syntax is:
ALTER TABLE footable DROP FOREIGN KEY fooconstraint;
The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.
I would think the following query would do it:
ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;
As everyone said above, you can easily delete a FK. However, I just noticed that it can be necessary to drop the KEY itself at some point. If you have any error message to create another index like the last one, I mean with the same name, it would be useful dropping everything related to that index.
ALTER TABLE your_table_with_fk
drop FOREIGN KEY name_of_your_fk_from_show_create_table_command_result,
drop KEY the_same_name_as_above
Check what's the CONSTRAINT name and the FOREIGN KEY name:
SHOW CREATE TABLE table_name;
Remove both the CONSTRAINT name and the FOREIGN KEY name:
ALTER TABLE table_name
DROP FOREIGN KEY the_name_after_CONSTRAINT,
DROP KEY the_name_after_FOREIGN_KEY;
Hope this helps!
Hey I followed some sequence above,
and found some solution.
SHOW CREATE TABLE footable;
You will get FK Constrain Name like
ProjectsInfo_ibfk_1
Now you need to remove this constraints. by alter table commantd
alter table ProjectsInfo drop foreign key ProjectsInfo_ibfk_1;
Then drop the table column,
alter table ProjectsInfo drop column clientId;
Here's a way to drop foreign key constraint, it will work.
ALTER TABLE location.location_id
DROP FOREIGN KEY location_ibfk_1;
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:
SHOW CREATE TABLE region;
This should show you a row ,at left upper corner click the +option ,the click the full text raio button then click the go .there you will get the name of the index, something like this:
CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION
Now simply issue an:
alter table region drop foreign key region_ibfk_1;
or
more simply just type:-
alter table TableName drop foreign key TableName_ibfk_1;
remember the only thing is to add _ibfk_1 after your tablename to make like this:- TableName_ibfk_1
first need to get actual constrain name by this query
SHOW CREATE TABLE TABLE_NAME
This query will result constrain name of the foreign key, now below query will drop it.
ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1
last number in above constrain name depends how many foreign keys you have in table
You can not drop the foreign key column because it is being referenced from the table assignmentStuff. So you should first drop the foreign key constraint assignmentStuff.assignmentIDX.
A similar question has already been asked here. Check also here for more info.
Try this:
alter table Documents drop
FK__Documents__Custo__2A4B4B5E
step1: show create table vendor_locations;
step2: ALTER TABLE vendor_locations drop foreign key vendor_locations_ibfk_1;
it worked for me.