I am trying to create a relation between a field 'fldEmpID' in my Employees table to a foreign composite key which consists of fldEmpID and fldEventID but it is not allowing the relation to be created. I don't understand why this relation won't work, I was able to create a similar relation between fldEventID from an Events to the composite key. Both fldEmpID fields in each table are int(11). What can I do to create this relation?
The following are the two tables... (I would like to keep the composite key on the table to the right as it helps to prevent duplicates and works well)
It seems to work as expected for me. I created the tables and used the Designer tab to create the relation (by selecting the "Create relation" icon, then clicking fldEmpId in table a, and finally selecting fldEmpID in table b).
For reference, I pasted below the structure of my table (which includes the keys and restraints)
CREATE TABLE IF NOT EXISTS `a` (
`fldEmpId` int(11) NOT NULL,
`fldEmpName` varchar(50) NOT NULL,
`fldEmail` varchar(50) NOT NULL,
`fldPassHash` varchar(50) NOT NULL,
`fldPassSalt` varchar(50) NOT NULL,
`fldAdmin` enum('1','2') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `b` (
`fldEmpID` int(11) NOT NULL,
`fldEventID` bigint(20) unsigned NOT NULL,
`fldDTAdded` datetime NOT NULL,
`fldDTRemoved` datetime NOT NULL,
`fldPosition` enum('0','1','2','3','4','5') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `a`
ADD PRIMARY KEY (`fldEmpId`);
ALTER TABLE `b`
ADD PRIMARY KEY (`fldEmpID`), ADD UNIQUE KEY `fldEventID` (`fldEventID`);
ALTER TABLE `a`
MODIFY `fldEmpId` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `b`
ADD CONSTRAINT `fk` FOREIGN KEY (`fldEmpID`) REFERENCES `a` (`fldEmpId`);
Related
I have a scenario of of three classes .I am planning to make the database for it .The relationship between them is :
1 customer is related with many items and many dv-vouchers.
1 item is related with many customer and many dv-vouchers.
1 dv-vouchers is related with 1 customer and many items .
public Customer
{
int cust_id;
list<items> items;
list<dvouchers> dvouchers;
}
public items
{
int itm_id;
list<Customer> customers;
list<dvouchers> dvouchers;
}
public dvouchers
{
int dv_id;
Customer customer;
list<items> items;
}
First of all what can be the design for database tables for above classes, fk_constraints and relationship tables ?
Second Do I need to perform Insert and Update operation on both the relationship tables along db table ? Please Help .
1.
You need two tables Customer_Item and Item_Dvoucher for relationship many-to-many and field cust_id in table Dvoucher for one-to-one relationship.
2.
You need to insert or update data in base tables Customer, Item and Dvoucher. Then you need to add or remove relationship in table Customer_Item and Items_Dvoucher. Also fill field cust_id in table Dvoucher.
Generated in mysql:
CREATE TABLE `Customer` (
`cust_id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`cust_id`)
)
CREATE TABLE `Dvoucher` (
`dv_id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) DEFAULT NULL,
`cust_id` INT(11) DEFAULT NULL,
PRIMARY KEY (`dv_id`),
KEY `cust_id` (`cust_id`),
CONSTRAINT `Dvoucher_ibfk_1` FOREIGN KEY (`cust_id`) REFERENCES `Customer` (`cust_id`)
)
CREATE TABLE `Item` (
`item_id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`item_id`)
)
CREATE TABLE `Customer_Item` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`cust_id` INT(11) DEFAULT NULL,
`item_id` INT(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `cust_id` (`cust_id`),
KEY `item_id` (`item_id`),
CONSTRAINT `Customer_Item_ibfk_1` FOREIGN KEY (`cust_id`) REFERENCES `Customer` (`cust_id`),
CONSTRAINT `Customer_Item_ibfk_2` FOREIGN KEY (`item_id`) REFERENCES `Item` (`item_id`)
)
CREATE TABLE `Item_Dvoucher` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`item_id` INT(11) DEFAULT NULL,
`dv_id` INT(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `item_id` (`item_id`),
KEY `dv_id` (`dv_id`),
CONSTRAINT `Item_Dvoucher_ibfk_1` FOREIGN KEY (`item_id`) REFERENCES `Item` (`item_id`),
CONSTRAINT `Item_Dvoucher_ibfk_2` FOREIGN KEY (`dv_id`) REFERENCES `Dvoucher` (`dv_id`)
)
In SQLite:
CREATE TABLE customer(cust_id INTEGER PRIMARY KEY, ...);
CREATE TABLE item(itm_id INTEGER PRIMARY KEY, ...);
CREATE TABLE dvoucher(dv_id INTEGER PRIMARY KEY, cust_id REFERENCES customer(cust_id), ...);
CREATE TABLE dvoucher_item(dv_id REFERENCES dvoucher(dv_id), itm_id REFERENCES item(itm_id));
CREATE TABLE customer_item(cust_id INTEGER PRIMARY KEY, itm_id REFERENCES item(itm_id));
As #Andrei solution to MySQL, using dvoucher.cust_id to link dvoucher to costumer, and tables dvoucher_item and customer_item to many to many links.
I have these classes, abbreviated for practical reasons:
class CV {
Date dateCreated
static hasMany=[proposals: Proposal]
}
class Proposal {
String name
Date date_started
static hasMany = [CVs: CV]
static belongsTo = CV
}
Grails creates tables for both these classes, and a third class named "cv_proposals" joining them. So far, so good. I have data in both the CV and the Proposal tables, they both have autoincremented "id" values. All good.
in Oracle MySQL Workbench, I try to manually add values to the joining table to get some dummy data to work with. I get an error message with this trace:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
(cvreg_utv.cv_proposals, CONSTRAINT FK17D946F55677A672 FOREIGN KEY (cv_id) REFERENCES cv (id))
I made sure both the tables had several lines of data in them, and that I could edit both of them separately.
After trying dropping and recreating the table, altering the classes back and forth, I'm kind of convinced that this operation somehow has to be done through a running Grails application. So I write this script in a controller and run it:
def g = CV.get(1)
Proposal proposal = g.addToProposals(new Proposal(
name: "SavingTest",
date_started: new Date())).save()
I still get the same error, though. Is this not the right way to define a proposal that is connected to a certain CV? Am I wrong in using a many-to-many connection here somehow?
Edit: adding the schema-create script for the joining table
delimiter $$
CREATE TABLE `cv_proposals` (
`proposal_id` bigint(20) NOT NULL,
`cv_id` bigint(20) NOT NULL,
PRIMARY KEY (`cv_id`,`proposal_id`),
KEY `FK17D946F55677A672` (`cv_id`),
KEY `FK17D946F5F7217832` (`proposal_id`),
CONSTRAINT `FK17D946F5F7217832` FOREIGN KEY (`proposal_id`) REFERENCES `proposal` (`id`),
CONSTRAINT `FK17D946F55677A672` FOREIGN KEY (`cv_id`) REFERENCES `cv` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
And the CV table:
CREATE TABLE `cv` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`version_name` varchar(255) DEFAULT NULL,
`date_created` datetime NOT NULL,
`last_updated` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `FKC734A9AB992` (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=101 DEFAULT CHARSET=latin1$$
And the Proposal table:
CREATE TABLE `proposal` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version` bigint(20) NOT NULL,
`date_ended` datetime NOT NULL,
`date_started` datetime NOT NULL,
`description` varchar(500) DEFAULT NULL,
`name` varchar(500) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1$$
This is the insert script I tried to run:
INSERT INTO `cvreg_utv`.`cv_proposals` (`proposal_id`, `cv_id`)
VALUES ('1', '1');
You crated the tables manually? It's interesting that cv table is using MyISAM engine and the others uses InnoDB.
I think you want to use InnoDB to all your tables, since this engine is transactional. In my test, I also was unable to create the cv_proposals table until I changed the cv creation:
CREATE TABLE cv (
id bigint(20) NOT NULL AUTO_INCREMENT,
version bigint(20) NOT NULL,
user_id bigint(20) NOT NULL,
version_name varchar(255) DEFAULT NULL,
date_created datetime NOT NULL,
last_updated datetime NOT NULL,
PRIMARY KEY (id),
KEY FKC734A9AB992 (user_id)
) ENGINE=InnoDB AUTO_INCREMENT=101
After that, the insert's worked smoothly.
what kind of relation (1:1, 1:m, m:m, whatever) there is between this two tables?
CREATE TABLE IF NOT EXISTS `my_product` (
`id` int(11) NOT NULL auto_increment,
`price` float default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `my_product_i18n` (
`id` int(11) NOT NULL,
`culture` varchar(7) NOT NULL,
`name` varchar(50) default NULL,
PRIMARY KEY (`id`,`culture`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `my_product_i18n`
ADD CONSTRAINT `my_product_i18n_FK_1` FOREIGN KEY (`id`) REFERENCES `my_product` (`id`);
It is 1:m you can have several different culture in my_product_i18n connected for each id.
Edit:
It is PRIMARY KEY ('id','culture') in conjunction with the constraint that tells that you can have many my_product_i18n.
1 to "maybe" - there's no guarantee that there will be a row in my_product_i18n, and the composite primary key of id and culture mean that you could have multiple rows for a given id, provided that those rows are of different cultures.
This is a 1:M relationship. One row in my_product can have 0, 1, or more rows in my_product_i18n based off of the culture column.
How do I set the name of a primary key when creating a table?
For example here I'm trying to create a primary key with the name 'id', but this is invalid SQL. Can you tell me the correct way to do this?
CREATE TABLE IF NOT EXISTS `default_test`
(
`default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY `id`,
`default_test`.`name` LONGTEXT NOT NULL
)
Clarification
I'd like to specify the name of the primary key - rather than the default name of "PRIMARY" I'd like it to be called "id" or perhaps "primary_id", so if I were to later run SHOW INDEXES FROM default_test, the Key_name will be something I have specified.
Alternatively and more widely supported:
CREATE TABLE IF NOT EXISTS `default_test` (
`default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT,
`default_test`.`name` LONGTEXT NOT NULL,
PRIMARY KEY (`id`)
)
UPDATE
Based on the clarification, you could replace the last definition above with the following if you are to specify the index name:
CONSTRAINT `pk_id` PRIMARY KEY (`id`)
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
[...] In MySQL, the name of a PRIMARY KEY is PRIMARY. [...]
CREATE TABLE IF NOT EXISTS `default_test` (
`default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT,
`default_test`.`name` LONGTEXT NOT NULL,
PRIMARY KEY (`id`)
)
You shouldn't specify the column name when you specify the primary key column name directly inline with the column definition, so:
CREATE TABLE IF NOT EXISTS `default_test` (
`default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`default_test`.`name` LONGTEXT NOT NULL
);
Alternativly you could do:
CREATE TABLE IF NOT EXISTS `default_test` (
`default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT ,
`default_test`.`name` LONGTEXT NOT NULL ,
PRIMARY KEY `default_test_id_pkey` (`id`)
);
You don't have to specify the column name again, because you already specified it as part of the current field definition - just say PRIMARY KEY.
CREATE TABLE IF NOT EXISTS `default_test` (
`id` SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` LONGTEXT NOT NULL
)
Alternatively, you can specify it separately later:
CREATE TABLE IF NOT EXISTS `default_test` (
`id` SMALLINT NOT NULL AUTO_INCREMENT,
`name` LONGTEXT NOT NULL,
PRIMARY KEY(`id`)
)
I want to create a database in which there's an n x m relationship between the table drug and the table article and an n x m relationship between the table target and the table article.
I get the error: Cannot delete or update a parent row: a foreign key constraint fails
What do I have to change in my code?
DROP TABLE IF EXISTS `textmine`.`article`;
CREATE TABLE `textmine`.`article` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Pubmed ID',
`abstract` blob NOT NULL,
`authors` blob NOT NULL,
`journal` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `textmine`.`drugs`;
CREATE TABLE `textmine`.`drugs` (
`id` int(10) unsigned NOT NULL COMMENT 'This ID is taken from the biosemantics dictionary',
`primaryName` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `textmine`.`targets`;
CREATE TABLE `textmine`.`targets` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`primaryName` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `textmine`.`containstarget`;
CREATE TABLE `textmine`.`containstarget` (
`targetid` int(10) unsigned NOT NULL,
`articleid` int(10) unsigned NOT NULL,
KEY `target` (`targetid`),
KEY `article` (`articleid`),
CONSTRAINT `article` FOREIGN KEY (`articleid`) REFERENCES `article` (`id`),
CONSTRAINT `target` FOREIGN KEY (`targetid`) REFERENCES `targets` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `textmine`.`contiansdrug`;
CREATE TABLE `textmine`.`contiansdrug` (
`drugid` int(10) unsigned NOT NULL,
`articleid` int(10) unsigned NOT NULL,
KEY `drug` (`drugid`),
KEY `article` (`articleid`),
CONSTRAINT `article` FOREIGN KEY (`articleid`) REFERENCES `article` (`id`),
CONSTRAINT `drug` FOREIGN KEY (`drugid`) REFERENCES `drugs` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You are trying to create tables out of order.
For example you are trying to create contiansdrug table which refers to table drugs before drugs table.
Remember that any SQL, even DDL, tries to leave database in consistent state.
I would recommend putting the commands in proper order. Alternatively you have options to turn off the checks temporarily and run the creation scrip inside transaction, see the instructions here
Relevant section is
SET AUTOCOMMIT = 0;
SET FOREIGN_KEY_CHECKS=0;
.. your script..
SET FOREIGN_KEY_CHECKS = 1;
COMMIT;
SET AUTOCOMMIT = 1;
EDIT:
OK, try not to have same names for constraints. Reading the fine manual enlightens:
If the CONSTRAINT symbol clause is
given, the symbol value must be unique
in the database. If the clause is not
given, InnoDB creates the name
automatically.
EDIT2:
To spell it out, you have duplicate constrain symbol article, rename it and all will be fine.
Standard practice is if you name your constrains to use names that describe what is related, for example containsdrug_acticelid_article_id (firsttablename_column_secondtablename_column) would be unique and descriptive.
I solved the problem by not declaring the Foreign Key inside of MySql but simply declaring them as ints.