Database design MySQL using foreign keys - mysql

I'm having some a little trouble understanding how to handle the database end of a program I'm making. I'm using an ORM in Kohana, but am hoping that a generalized understanding of how to solve this issue will lead me to an answer with the ORM.
I'm writing a program for users to manage their stock research information. My tables are basically like so:
CREATE TABLE tags(
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
tags VARCHAR(30),
UNIQUE(tags)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE stock_tags(
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
tag_id INT NOT NULL,
stock_id INT NOT NULL,
FOREIGN KEY (tag_id) REFERENCES tags(id),
FOREIGN KEY(stock_id) REFERENCES stocks(id) ON DELETE CASCADE
)
ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE notes(
id INT AUTO_INCREMENT NOT NULL,
stock_id INT NOT NULL,
notes TEXT NOT NULL,
FOREIGN KEY (stock_id) REFERENCES stocks(id) ON DELETE CASCADE,
PRIMARY KEY(id)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE links(
id INT AUTO_INCREMENT NOT NULL,
stock_id INT NOT NULL,
links VARCHAR(2083) NOT NULL,
FOREIGN KEY (stock_id) REFERENCES stocks(id) ON DELETE CASCADE,
PRIMARY KEY(id)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;
How would I get all the attributes of a single stock, including its links, notes, and tags? Do I have to add links, notes, and tags columns to the stocks table and then how do you call it? I know this differs using an ORM and I'd assume that I can use join tables in SQL.
Thanks for any help, this will really help me understand the issue a lot better.

You will have to link the tables together using JOINS
Something like
SELECT *
FROM stocks s INNER JOIN
stock_tags st ON s.id = st.stock_id INNER JOIN
tags t ON st.tag_id = t.id etc...

Related

Could a foreign key column has multivalue in one row from the same reference table?

I'm trying to create a database on MySQL Workbench. Is it legal if a foreign key column has a multivalue in one row? I want to do that because based on the event category the user would be allowed to see the event or not. Also, there could be multiple event categories for one event. I know that I can make a composite key to event table. But I'm wondering that can I have multivalue as a foreign key in one row?
Here is my Event table:
CREATE TABLE IF NOT EXISTS `mydb`.`EVENT` (
`eventID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`eventCategory` INT UNSIGNED NOT NULL,
`name` VARCHAR(45) NOT NULL,
`eventDescription` VARCHAR(280) NULL,
`date` DATETIME(1) NOT NULL,
`locationDescription` VARCHAR(45) NOT NULL,
`regionID` INT UNSIGNED NOT NULL,
PRIMARY KEY (`eventID`),
INDEX `fk_EVENT_category_1_idx` (`eventCategory` ASC) VISIBLE,
INDEX `fk_EVENT_region_1_idx` (`regionID` ASC) VISIBLE,
CONSTRAINT `fk_EVENT_region_1`
FOREIGN KEY (`regionID`)
REFERENCES `mydb`.`REGION` (`regionID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_EVENT_category_1`
FOREIGN KEY (`eventCategory`)
REFERENCES `mydb`.`CATEGORY` (`categoryID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
And I want to store multiple categories in one ro. I want to do that because based on those categories, some of the users wouldn't be allowed to see the event in the application.
Here is my category table:
CREATE TABLE IF NOT EXISTS `mydb`.`CATEGORY` (
`categoryID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`disorderID` INT UNSIGNED NOT NULL,
`categoryDescription` VARCHAR(45) NOT NULL,
PRIMARY KEY (`categoryID`, `disorderID`),
INDEX `fk_CATEGORY_disorder_1_idx` (`disorderID` ASC) VISIBLE,
CONSTRAINT `fk_CATEGORY_disorder_1`
FOREIGN KEY (`disorderID`)
REFERENCES `mydb`.`DISORDERS` (`disorderID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
And I want to store multiple categories in one ro. I want to do that because based on those categories, some of the users wouldn't be allowed to see the event in the application.
No. Don't got that way. This would denormalize your schema and make simple things utterly complex later on.
You have a many-to-many relationship between event and categories. The proper way to represent that is to create a third table, where each event/category table is stored on a separate row.
Something like:
create table event_categories (
event_id int not null,
category_id int not null,
primary key (event_id, category_id),
foreign key(event_id) references event(event_id),
foreign key(category_id) references category(category_id),
);

error 1215: database design with foreign key

I am trying to create three tables such as associate, manager and attendance. The attendance table should be having employee and manager details from the other two table which should enable marking the attendance. I created this SQL script. I'm not sure where I am making mistake.
CREATE TABLE associate (
id INT NOT NULL,
idmanager INT NOT NULL,
emp_id DATE NOT NULL,
emp_name VARCHAR(25) NOT NULL,
FOREIGN KEY (id) REFERENCES attendance (associate_id) ON DELETE CASCADE,
FOREIGN KEY (idmanager) REFERENCES attendance (manager_idmanager) ON DELETE CASCADE,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE manager (
id INT NOT NULL,
mgr_usr_id VARCHAR(15) NOT NULL,
mgr_name VARCHAR(25) NOT null,
KEY (id),
KEY (mgr_usr_id),
FOREIGN KEY (id) REFERENCES associate (idmanager) ON DELETE CASCADE,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INT NOT NULL,
manager_idmanager INT NOT NULL,
associate_id INT NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno)
) ENGINE=INNODB;
Screenshot
It's an issue of ordering. For example, the first statement executed is
CREATE TABLE associate (
which references attendance. However, the attendance table has not yet been created. Switch the order so that any tables that reference other tables come last.
Alternatively, don't put the FOREIGN KEY constraints in the CREATE statements, but them at the end of your script with ALTER TABLE statements. Consider:
CREATE TABLE associate (
id INT NOT NULL,
idmanager INT NOT NULL,
emp_id DATE NOT NULL,
emp_name VARCHAR(25) NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INT NOT NULL,
manager_idmanager INT NOT NULL,
associate_id INT NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno)
) ENGINE=INNODB;
ALTER TABLE associate ADD FOREIGN KEY (id) REFERENCES associate(id) ON DELETE CASCADE;
Edit
The above is just syntax. To model the requested problem consider orthogonality of information. You might also see/hear "normalization." The basic concept is this: have only one copy of your information. The schema should have a single point of authority for all data. For example, if a user has a birthdate, make sure you don't have an ancillary column that also stores their birthday; it's superfluous information and can lead to data errors.
In this case, what is the relationship? What must come first for the other to exist? Can an attendance be had without a manager? How about a manager without attendance? The former makes no sense. In this case then, I would actually use a third table, to form a hierarchy.
Then, consider that maybe roles change in a company. It would not behoove the DB architect to hard code roles as tables. Consider:
CREATE TABLE employee (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(25) NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE role (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
description VARCHAR(254) NOT NULL,
PRIMARY KEY( id ),
UNIQUE( name )
) ENGINE=INNODB;
INSERT INTO role (name, description) VALUES
('associate', 'An associate is a ...'),
('manager', 'A manager follows ...');
CREATE TABLE employee_role (
employee_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
PRIMARY KEY (employee_id, role_id),
FOREIGN KEY (idemployee_id) REFERENCES employee_id (id) ON DELETE CASCADE,
FOREIGN KEY (role_id) REFERENCES role (id) ON DELETE CASCADE
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INTEGER NOT NULL,
employee_id INTEGER NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno),
FOREIGN KEY (idemployee_id) REFERENCES employee_id (id) ON DELETE CASCADE
) ENGINE=INNODB;
From this schema, the attendance needs only one foreign key because everyone is an employee. Employee's can have multiple roles, and they can change. Further, role definitions can change without needing to resort to costly DDL statements (data definition layer changes, like ALTER TABLE), and can be modified with simple DML (data manipulation layer changes, like UPDATE TABLE). The former involves rewriting all entries in the tables, and changing schemas, while the latter involves changing individual entries.

Error code 1215: cannot add foreign key constraint MySQL

I'm having a problem creating a database in MySQL.
The error code:'Error code 1215: cannot add foreign key constraint' pops up when i try to implement my changes. I've paid attention to all the necessary things but i can't find the solution.
This error only happened after i added some tables after having made an initial database(which did work), so hopefully i'm not dealing with this problem throughout the whole project.
Here's a snippet of the code in which the error occurs, the foreign key that's not working correctly is 'tournament_id' referencing to 'id' in tournament:
CREATE DATABASE allin;
USE allin;
CREATE TABLE employee (
phone_number char(12) NOT NULL,
birth_date date NOT NULL,
tournament_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(phone_number),
FOREIGN KEY(tournament_id) REFERENCES tournament(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Second table:
CREATE TABLE tournament (
id int NOT NULL AUTO_INCREMENT,
date date NOT NULL,
time time NOT NULL,
cost decimal(5,2) NOT NULL,
min_players int NOT NULL,
min_age int NOT NULL,
max_age int NOT NULL,
location_id int NULL,
winner_id int NULL,
type varchar(40) NULL,
PRIMARY KEY(id),
FOREIGN KEY(winner_id) REFERENCES player(id) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY(location_id) REFERENCES event_location(id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The issue is here:
FOREIGN KEY(tournament_id) REFERENCES tournament(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
the above query is of CREATE TABLE employee. In this query, you are creating a FOREIGN KEY that refers to tournament(id), but as of now there is no tournament table exist in the specified database as the tournament table create query is reside below in the sequence.
I layman terms we can say, you are trying to refer a table column that
do not exist.
So to resolve this, run all you parent table creation query first, and than child table.
tournament_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(phone_number)
Hey, I don't think you could set another primary key while an "auto increment" already exist

Yii Database structure

I'm designing database for Yii web application and I'm not sure I'm doing it right way.
CREATE TABLE user
(
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(128) NOT NULL,
password VARCHAR(128) NOT NULL,
email VARCHAR(128) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE post
(
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(128) NOT NULL,
description TEXT NOT NULL,
media TEXT NOT NULL,
tag_id INTEGER NOT NULL,
status INTEGER NOT NULL,
create_time INTEGER,
update_time INTEGER,
user_id INTEGER NOT NULL,
CONSTRAINT FK_post_user FOREIGN KEY (user_id)
REFERENCES user (id) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE comment
(
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
content TEXT NOT NULL,
status INTEGER NOT NULL,
create_time INTEGER,
user_id INTEGER NOT NULL,
post_id INTEGER NOT NULL,
CONSTRAINT FK_comment_post FOREIGN KEY (post_id)
REFERENCES post (id) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE tag
(
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(128) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Problems:
1.) In post table I have tag_id. I was thinking to store all existing and newly added tags in tag table and then when someone use already existed tag or made new tag to add as tag_id to post table with ",". Is this the best solution?
2.) In comment table I have user_id and post_id. How I think foreign key are working there should be set 2 foreign keys in comment table? I tried that but got error.
3.) In post table there is media row. I'm going to store in this row location to uploaded image OR embed code from youtube/or any other source. Is this ok to use only same row for that or should I use seperated? 1 for images, 1 for embed code?
Thanks in advance
1) In case I'd use column with name tags instead tag_id where i'd keep serialized array of tag_id's from table tags
2) The problem i think because you tried add foreign keys with same name.
Try to use
CONSTRAINT FK_comment_post FOREIGN KEY
CONSTRAINT FK_comment_post_2 FOREIGN KEY
3) What will be if you'll decide to add another media info in post(pdf_file, or music). Add new column in table post it's not correct. i'd recommend you create additional table postmeta where you can create any type of content, and instead media use post_text. Like in wordpress.

Nesting of groups or elements

I'm fairly new in Mysql, but I have problem that I cannot solve. I will give you an example to demonstrate it. Please note that I know that (for current example) there are other simpler and more efficient ways to solve it... but just take it as an example of the required procedure.
First the data: The data would be the name of a Person.
CREATE TABLE person(
id INT,
name VARCHAR(100)
) TYPE=innodb;
Second: Group Creation... So this is fairly simple... and could easily done using a table 'group' with a foreignkey to person. These groups could be arbitrary, containing any number of persons, duplicated... or not... (that is simple!!)
Third: MY REAL PROBLEM--- I also would like to have Groups that have other Groups as elements (instead of persons). This is where a really get stuck, because I know how to create a groups of persons, a group of groups (having a self-referencing foreign key)... but I don't know how to create a group that MAY HAVE persons AND Groups.
I appreciate any suggestion to solve this issue.
Thank you very much for your comments.
Regards
ACombo
I'd go with firstly setting up the myGroup and person tables.
Secondly, I'd set up a myGroupGroup table with columns myGroupId, parentMyGroupId. This will allow you to relate group rows to child group rows i.e. "this group has these groups within it". If a group has no rows in this table then it has no child groups within it.
Thirdly, I'd set up a personGroup table with columns personId, myGroupId. This will allow you to relate person rows to a given group. If a group has no rows in this table then it has no persons within it.
CREATE TABLE person(
id INT UNSIGNED PRIMARY KEY,
name VARCHAR(100)
) ENGINE=innodb;
CREATE TABLE myGroup(
id INT UNSIGNED PRIMARY KEY,
groupName VARCHAR(100)
) ENGINE=innodb;
-- Holds groups within groups
CREATE TABLE myGroupGroup(
id INT UNSIGNED PRIMARY KEY,
myGroupId INT UNSIGNED,
parentMyGroupId INT UNSIGNED DEFAULT NULL,
CONSTRAINT `fk_myGroupGroup_group1` FOREIGN KEY (`parentMyGroupId`) REFERENCES `myGroup` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_myGroupGroup_group2` FOREIGN KEY (`myGroupId`) REFERENCES `myGroup` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=innodb;
-- Holds persons within a group
CREATE TABLE personGroup(
id INT,
personId int UNSIGNED NOT NULL,
myGroupId int UNSIGNED NOT NULL,
CONSTRAINT `fk_personGroup_group1` FOREIGN KEY (`myGroupId`) REFERENCES `myGroup` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_personGroup_person1` FOREIGN KEY (`personId`) REFERENCES `person` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=innodb;
I've tweaked your SQL a bit:
1) Replaced TYPE with ENGINE
2) Replaced table name group with myGroup (GROUP is a reserved word)
Good luck!
Alternative:
CREATE TABLE Entity
( EntityId INT --- this id could be AUTO_INCREMENT
, PRIMARY KEY (EntityId)
) ENGINE = InnoDB ;
CREATE TABLE Person
( PersonId INT --- but not this id
, PersonName VARCHAR(100)
, PRIMARY KEY (PersonId)
, FOREIGN KEY (PersonId)
REFERENCES Entity(EntityId)
) ENGINE = InnoDB ;
CREATE TABLE Grouping
( GroupingId INT --- and neither this id
, GroupingName VARCHAR(100)
, PRIMARY KEY (GroupingId)
, FOREIGN KEY (GroupingId)
REFERENCES Entity(EntityId)
) ENGINE = InnoDB ;
CREATE TABLE Belongs
( EntityId INT
, GroupingID INT
, PRIMARY KEY (EntityId, GroupingId)
, FOREIGN KEY (EntityId)
REFERENCES Entity(EntityId)
, FOREIGN KEY (GroupingID)
REFERENCES Grouping(GroupingId)
) ENGINE = InnoDB ;