Foreign Key Constraints In MySQL DB Gives Error - mysql

am trying to implement a foreign key constraint but the mysql keeps giving me an error There are two tables "groups" table and "members" table.I have a many to many relationship between these tables and therefore used a third table called "members_groups" table for the many to many relationship. Note: "groups" and "members" tables have been created and contain data but I now want to add the "members_groups" table. Below are the sql codes:
Below is the script for the members table.
CREATE TABLE IF NOT EXISTS `members` (
`member_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`email` varchar(50) NOT NULL,
`password` char(128) NOT NULL,
`salt` char(128) NOT NULL,
`group_id` bigint(64) unsigned NOT NULL,
`perm_override_add` bigint(64) unsigned NOT NULL,
`perm_override_remove` bigint(64) unsigned NOT NULL,
PRIMARY KEY (`member_id`),
KEY `member_id` (`member_id`)
) ENGINE=InnoDB;
script for the groups table
CREATE TABLE IF NOT EXISTS `groups` (
`group_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`group_name` varchar(50) NOT NULL,
`permission` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`group_id`)
) ENGINE=InnoDB
script for the members_groups table
CREATE TABLE members_groups
(
member_id INT(11) NOT NULL ,
group_id INT(10) NOT NULL ,
PRIMARY KEY (member_id, group_id),
FOREIGN KEY (member_id) REFERENCES members(member_id) ON UPDATE CASCADE,
FOREIGN KEY (group_id) REFERENCES groups(group_id) ON UPDATE CASCADE
) ENGINE = InnoDB
This is the error I get from the mysql admin console.
Thanks.

You need to make the type same in your table. In your groups table you have defined
`group_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
whereas in your members_groups table it is
group_id INT(10) NOT NULL ,
Try to make the change like
CREATE TABLE members_groups
(
member_id INT(11) NOT NULL ,
group_id INT(10) unsigned NOT NULL , --The datatype should be same as group_id in `groups` table
PRIMARY KEY (member_id, group_id),
FOREIGN KEY (member_id) REFERENCES members(member_id) ON UPDATE CASCADE,
FOREIGN KEY (group_id) REFERENCES `groups`(group_id) ON UPDATE CASCADE
) ENGINE = InnoDB;
SQL FIDDLE DEMO

Related

MySQL MariaDB wont create Table with a foreign key

I'm having a problem with my SQL Tables. So I have my Usertable:
CREATE TABLE IF NOT EXISTS `user` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NICKNAME` varchar(50) NOT NULL,
`PASSWORD` varchar(255) NOT NULL,
`EMAIL` varchar(50) DEFAULT NULL,
PRIMARY KEY (`NICKNAME`),
UNIQUE KEY `ID` (`ID`)
) ;
This table already exists and was created without any problems. I Want to create a score Table like this:
CREATE TABLE IF NOT EXISTS `scores` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NICKNAME` varchar(50) NOT NULL,
`HIGHSCORE` int(11) NOT NULL,
PRIMARY KEY (`ID`),
FOREIGN KEY (NICKNAME) REFERENCES USER(Nickname)
)
On execution of the query I get this errormassage:
**#1005 - Kann Tabelle `xxxxx`.`scores` nicht erzeugen (Fehler: 150 "Foreign key constraint is incorrectly formed") (Details…)**
Its in German and says cant create Table, Error 150, I cant see where the key constraint is wrong, I used the same syntax in postgreSQL and it worked fine, but somehow MySQL is not accepting it. Any Ideas?
That is strange. If nickname is indeed the primary key, then your code should work.
It is much more nature, though, to use the auto-incremented column as the primary key. If you want the nickname, then use a join when you query.
So:
CREATE TABLE IF NOT EXISTS `scores` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
UserId int(11) NOT NULL,
`NICKNAME` varchar(50) NOT NULL,
`HIGHSCORE` int(11) NOT NULL,
PRIMARY KEY (`ID`),
FOREIGN KEY (UserId) REFERENCES USER(Id)
);
user - is a keyword.
It may be a good idea to use another table name e.g. "tblUser",
or use quotes again ``
FOREIGN KEY (NICKNAME) REFERENCES `USER`(ID)
Thanks to Mr. Gordon Linoff I was able to find my Mistake:
I had to declare NICKNAME to be declared UNIQUE, only then the FOREIGN KEY constraint could be added to other tables
CREATE TABLE IF NOT EXISTS `user` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NICKNAME` varchar(50) NOT NULL,
`PASSWORD` varchar(255) NOT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
PRIMARY KEY (`NICKNAME`),
UNIQUE KEY `ID` (`ID`),
UNIQUE KEY `NICKNAME` (`NICKNAME`)
);

SQL 5.6 Foreign key statement error

i am new to SQL and i am trying out some simple create table statement but i am facing some problem with the foreign key at EMPLOYEEGROUP table. Below is a part of my create table statement
CREATE TABLE `User` (
`Userid` int(11) NOT NULL AUTO_INCREMENT,
`Username` VARCHAR(15) NOT NULL,
`Password` VARCHAR(15) NOT NULL,
PRIMARY KEY (Userid)
);
CREATE TABLE `Group` (
`GroupID` int(11) NOT NULL AUTO_INCREMENT,
`GroupName` VARCHAR(15) NOT NULL,
PRIMARY KEY (GroupID)
);
CREATE TABLE `EMPLOYEEGROUP` (
`EmployeeID` int(11) NOT NULL,
`AssignedGrp` int(11) NOT NULL,
CONSTRAINT EMPLOYEEGROUP_FK1 FOREIGN KEY (EmployeeID) REFERENCES User (Userid),
CONSTRAINT EMPLOYEEGROUP_FK2 FOREIGN KEY (AssignedGrp) REFERENCES Group (GroupID)
);
There is some issue with my EMPLOYEEGROUP_FK2 statement which i can't seem to solve it. any help would be appreciated. Thank you
In mysql GROUP is a reserved keyword. and you used group as table name
. but in table name you write group with `` . and when you take reference of group table you write group without ``. simple add `` in group name
Try blow query. it execute in my system hopfully execute also your system
CREATE TABLE `User` (
`Userid` int(11) NOT NULL AUTO_INCREMENT,
`Username` VARCHAR(15) NOT NULL,
`Password` VARCHAR(15) NOT NULL,
PRIMARY KEY (Userid)
);
CREATE TABLE `Group` (
`GroupID` int(11) NOT NULL AUTO_INCREMENT,
`GroupName` VARCHAR(15) NOT NULL,
PRIMARY KEY (GroupID)
);
CREATE TABLE `EMPLOYEEGROUP` (
`EmployeeID` int(11) NOT NULL,
`AssignedGrp` int(11) NOT NULL,
CONSTRAINT EMPLOYEEGROUP_FK1 FOREIGN KEY (EmployeeID) REFERENCES User (Userid),
CONSTRAINT EMPLOYEEGROUP_FK2 FOREIGN KEY (AssignedGrp) REFERENCES `Group` (GroupID)
);

Getting data that is difficult connected with the input data, SQL Query

Firstly, want to ask you (so my question would be more clear for you) if there an online database diagram tool (?) in which I can input my sql code and it will draw diagramm (with tables and their relationships) for me.
I found this question and tried some tools, but most of them can only create tables and relationships between them, but not allow to import my sql.
(2)
I need to get all classes connected with Teacher.
There are two types of connection: teacher may be the form-master or teacher may taugh this class.
How to get all classes which are connected to teacher.
(3) 1 more additional question: Am I right with constraints?
SQL Scheme (scheme on sqlfiddle.com):
CREATE TABLE `Subject` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
CREATE TABLE `Teacher` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`firstname` VARCHAR(50) NOT NULL,
`midname` VARCHAR(50) NOT NULL,
`lastname` VARCHAR(50) NOT NULL,
`address` VARCHAR(100) NOT NULL,
`birthdate` DATE NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `Class` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`digit` INT(11) NOT NULL,
`char` VARCHAR(50) NOT NULL,
`teacher_id` INT(11) NOT NULL,
PRIMARY KEY (`id`),
INDEX `FK_Class_Teacher` (`teacher_id`),
CONSTRAINT `FK_Class_Teacher` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`id`)
);
CREATE TABLE `ClassVsSubject` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`subject_id` INT(11) NOT NULL,
`class_id` INT(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `subject_id_class_id` (`subject_id`, `class_id`),
INDEX `FK_ClassVsSubject_Class` (`class_id`),
CONSTRAINT `FK_ClassVsSubject_Class` FOREIGN KEY (`class_id`) REFERENCES `class` (`id`),
CONSTRAINT `FK_ClassVsSubject_Subject` FOREIGN KEY (`subject_id`) REFERENCES `subject` (`id`)
);
CREATE TABLE `TeacherVsSubject` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`teacher_id` INT(11) NOT NULL,
`subject_id` INT(11) NOT NULL,
PRIMARY KEY (`id`),
INDEX `FK_TeacherVsSubject_Teacher` (`teacher_id`),
INDEX `FK_TeacherVsSubject_Subject` (`subject_id`),
CONSTRAINT `FK_TeacherVsSubject_Teacher` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`id`),
CONSTRAINT `FK_TeacherVsSubject_Subject` FOREIGN KEY (`subject_id`) REFERENCES `subject` (`id`)
);
For your second question, use something like:
select *
from Class
where teacher_id = 1
union
select Class.*
from Class
join ClassVsSubject on Class.id = ClassVsSubject.class_id
join TeacherVsSubject on ClassVsSubject.subject_id = TeacherVsSubject.subject_id
where TeacherVsSubject.teacher_id = 1
As you did not state which teacher is the starting point, I used that with id 1.
Please note that union gets rid of duplicate entries, there is no need to treat this separately.
For your data model (question 3), I think one gotcha is that you need different entries in the subject table for different classes and the same subject like 'Maths' or 'English', otherwise, the joins will not work:
Let's say subject "English" has id 1. Now, if the class with id 1 and the class with id 2 both have this subject, you would have the following data in ClassVsSubject:
class_id subject_id
1 1
2 1
How do you want to enter into table TeacherVsSubject that the teacher with id 5 teaches English in class 1, but not in class 2? You cannot! If you enter a record with subject_id 1 and teacher_id 5, this would apply to all classes.
To remedy that, you could make one table from the two ClassVsSubject and TeacherVsSubject. This would be like this:
CREATE TABLE `ClassVsSubjectVsTeacher` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`subject_id` INT(11) NOT NULL,
`class_id` INT(11) NOT NULL,
`teacher_id` INT(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `subject_id_class_id` (`subject_id`, `class_id`, `teacher_id`),
INDEX `FK_ClassVsSubjectVsTeacher_Class` (`class_id`),
INDEX `FK_ClassVsSubjectVsTeacher_Teacher` (`teacher_id`),
INDEX `FK_ClassVsSubjectVsTeacher_Subject` (`subject_id`),
CONSTRAINT `FK_ClassVsSubjectVsTeacher_Class` FOREIGN KEY (`class_id`) REFERENCES `class` (`id`),
CONSTRAINT `FK_ClassVsSubjectVsTeacher_Teacher` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`id`),
CONSTRAINT `FK_ClassVsSubjectVsTeacher_Subject` FOREIGN KEY (`subject_id`) REFERENCES `subject` (`id`)
);
For the data model, you would not need the id column here, the primary key could be a combined key across all three foreign keys. But - depending on client software - it may be useful to have it. E. g. some OR mapping tools require a single column primary key.
Try this: select * from Class where teacher_id = some_id_from_Teacher_table

#1215 - Cannot add foreign key constraint

I have this weird issue with creation of foreign key.
Given 2 tables:
CREATE TABLE IF NOT EXISTS `groupdeals` (
`groupdeals_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`product_id` int(10) NOT NULL,
`merchant_id` int(11) NOT NULL,
`minimum_qty` int(11) NOT NULL,
`maximum_qty` int(11) NOT NULL,
`target_met_email` int(11) NOT NULL,
`coupon_barcode` text NOT NULL,
`coupon_merchant_address` int(11) NOT NULL,
`coupon_merchant_contact` int(11) NOT NULL,
`coupon_expiration_date` date DEFAULT NULL,
`coupon_price` int(11) NOT NULL,
`coupon_fine_print` int(11) NOT NULL,
`coupon_highlights` int(11) NOT NULL,
`coupon_merchant_description` int(11) NOT NULL,
`coupon_business_hours` int(11) NOT NULL,
`coupon_merchant_logo` int(11) NOT NULL,
`coupon_additional_info` text NOT NULL,
`position` int(11) NOT NULL,
PRIMARY KEY (`groupdeals_id`),
KEY `groupdeals_id` (`groupdeals_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and
CREATE TABLE IF NOT EXISTS `groupdeals_coupons` (
`coupon_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`groupdeals_id` int(11) NOT NULL,
`order_item_id` int(11) NOT NULL,
`coupon_code` varchar(255) NOT NULL DEFAULT '',
`redeem` varchar(255) NOT NULL DEFAULT '',
`status` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`coupon_id`),
KEY `fk_groupdeals_coupons_groupdeals1_idx` (`groupdeals_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I try to add foreign key by executing following query:
ALTER TABLE `groupdeals_coupons`
ADD CONSTRAINT `fk_groupdeals_coupons_groupdeals1`
FOREIGN KEY (`groupdeals_id`)
REFERENCES `groupdeals` (`groupdeals_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
All I receive is Error:
#1215 - Cannot add foreign key constraint
Show engine innodb status
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2013-08-17 13:47:49 7ff5dbb2c700 Error in foreign key constraint of table xxxxx/#sql-7b23_282b1a:
FOREIGN KEY (`groupdeals_id`)
REFERENCES `groupdeals` (`groupdeals_id`)
ON DELETE CASCADE
ON UPDATE CASCADE:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
The column groupdeals.groupdeals_id is a primary one, so I really can't understand where is a problem :|
Any hints?
Server type: Percona Server
Server version: 5.6.11-rc60.3-log - Percona Server (GPL), Release 60.3
Your types are inconsistent:
CREATE TABLE IF NOT EXISTS `groupdeals` (
`groupdeals_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
CREATE TABLE IF NOT EXISTS `groupdeals_coupons` (
[...]
`groupdeals_id` int(11) NOT NULL,
As you will see, in one table you have int unsigned. In the other, just int.
BTW, I noticed you have two keys on groupdeals_id. Is that on purpose?
CREATE TABLE IF NOT EXISTS `groupdeals` (
[...]
PRIMARY KEY (`groupdeals_id`),
KEY `groupdeals_id` (`groupdeals_id`)
Try these two steps to add foreign key:-
alter table groupdeals_coupons modify groupdeals_id int unsigned not null default 0;
ALTER TABLE groupdeals_coupons ADD CONSTRAINT fk_groupdeals_coupons_groupdeals1 FOREIGN KEY (groupdeals_id) references groupdeals (roupdeals_id);

Mysql connect tables through foreign key, depends from field type

Mysql database question. There is system with objects(Domains). Each domain has own table. All objects has unique 16 varchar id - guid
CREATE TABLE `guid` (
`guid` varchar(16) NOT NULL,
`obj_type` varchar(45) NOT NULL,
`obj_id` varchar(45) NOT NULL,
`actived` tinyint(4) NOT NULL DEFAULT '1',
PRIMARY KEY (`guid`)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(150) NOT NULL,
/*....*/
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `catalog` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(150) NOT NULL,
/*....*/
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
I would like connect table guid(fields: obj_type, obj_id) and domain tables(field:id) through foreign key.
Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table. The parent and child tables must both be InnoDB tables. They must not be TEMPORARY tables.
CREATE TABLE product
(
id INT(11) NOT NULL auto_increment,
name VARCHAR(150) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (id) REFERENCES guid (guid )
)
engine=myisam
DEFAULT charset=utf8;