Designing a mysql database - mysql

I need to design a database that will:
Store Users, Quizzes and Resources (like articles, books, blog posts, etc.) and Users. The User will take a quiz when they first sign up, then their answers will determine what resources to suggest to them.
Here is what I have so far, which is a sql file that creates every table I need.
DROP TABLE IF EXISTS user_questions_answer;
DROP TABLE IF EXISTS user_questions_not_selected;
DROP TABLE IF EXISTS questions_choices;
DROP TABLE IF EXISTS questions;
DROP TABLE IF EXISTS quizes;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS Event_Table;
DROP TABLE IF EXISTS Congregations;
DROP TABLE IF EXISTS Resources;
DROP TABLE IF EXISTS Ensembles;
DROP TABLE IF EXISTS Topics;
DROP TABLE IF EXISTS Languages;
DROP TABLE IF EXISTS Resource_Tags;
DROP TABLE IF EXISTS Resource_Types;
DROP TABLE IF EXISTS Authors;
DROP TABLE IF EXISTS Social_Media_Connections;
DROP TABLE IF EXISTS Ethnicities;
DROP TABLE IF EXISTS Cong_Type;
DROP TABLE IF EXISTS Worship_Types;
DROP TABLE IF EXISTS Instrument_Types;
DROP TABLE IF EXISTS Song_Types;
DROP TABLE IF EXISTS Denominations;
DROP TABLE IF EXISTS Event_Types;
DROP TABLE IF EXISTS Parent_Org;
DROP TABLE IF EXISTS tags;
CREATE TABLE Authors (
id int unsigned auto_increment,
name varchar(128),
PRIMARY KEY (id),
website varchar(128),
email varchar(64)
);
CREATE TABLE Resource_Types (
id int unsigned auto_increment,
name varchar(128),
PRIMARY KEY (id)
);
CREATE TABLE Resource_Tags (
id int unsigned auto_increment,
name varchar(128),
PRIMARY KEY (id)
);
CREATE TABLE Languages (
id int unsigned auto_increment,
name varchar(128),
PRIMARY KEY (id)
);
CREATE TABLE Topics (
id int unsigned auto_increment,
name varchar(128),
PRIMARY KEY (id)
);
CREATE TABLE Ensembles (
id int unsigned auto_increment,
name varchar(128),
PRIMARY KEY (id)
);
CREATE TABLE Parent_Org (
id int unsigned auto_increment,
name varchar(128),
PRIMARY KEY (id)
);
CREATE TABLE Event_Types (
id int unsigned auto_increment,
name varchar(64),
PRIMARY KEY (id)
);
CREATE TABLE Denominations (
id int unsigned auto_increment,
name varchar(64),
PRIMARY KEY (id)
);
CREATE TABLE Song_Types (
id int unsigned auto_increment,
name varchar(64),
PRIMARY KEY (id)
);
CREATE TABLE Instrument_Types (
id int unsigned auto_increment,
name varchar(64),
PRIMARY KEY (id)
);
CREATE TABLE Worship_Types (
id int unsigned auto_increment,
name varchar(64),
PRIMARY KEY (id)
);
CREATE TABLE Cong_Type (
id int unsigned auto_increment,
name varchar(64),
PRIMARY KEY (id)
);
CREATE TABLE Ethnicities (
id int unsigned auto_increment,
name varchar(64),
PRIMARY KEY (id)
);
CREATE TABLE Social_Media_Connections(
id int unsigned auto_increment,
name varchar(64),
PRIMARY KEY (id),
type varchar(32),
link varchar(64)
);
CREATE TABLE Congregations (
cong_id int unsigned auto_increment,
PRIMARY KEY (cong_id),
cong_name varchar(64),
website varchar(64),
cong_city varchar(64),
cong_state varchar(64),
cong_country varchar(64),
hymn_soc_members boolean default False,
priest_attire varchar(64),
avg_attendance float,
denomination_id int unsigned not null,
song_types_id int unsigned not null,
instrument_types_id int unsigned not null,
worship_types_id int unsigned not null,
cong_type_id int unsigned not null,
ethnicity_types_id int unsigned not null,
FOREIGN KEY (denomination_id)
REFERENCES Denominations (id),
FOREIGN KEY (song_types_id)
REFERENCES Song_Types(id),
FOREIGN KEY (instrument_types_id)
REFERENCES Instrument_Types(id),
FOREIGN KEY (worship_types_id)
REFERENCES Worship_Types(id),
FOREIGN KEY (cong_type_id)
REFERENCES Cong_Type(id),
FOREIGN KEY (ethnicity_types_id)
REFERENCES Ethnicities(id)
);
CREATE TABLE Event_Table(
event_id int unsigned auto_increment,
PRIMARY KEY(event_id),
event_title varchar(128),
website varchar(128),
theme_or_topic varchar(128),
event_desc text(256),
event_start_date date,
event_start_time time,
event_end_date date,
event_end_time time,
registration_cost int unsigned default 0,
event_city varchar(64),
event_state varchar(32),
event_country text,
hymn_soc_member_involved boolean default False,
parent_org_id int unsigned,
FOREIGN KEY (parent_org_id)
REFERENCES Parent_Org (id),
event_type_id int unsigned,
FOREIGN KEY (event_type_id)
REFERENCES Event_Types(id)
);
CREATE TABLE Resources (
id int unsigned auto_increment,
PRIMARY KEY (id),
title varchar(128),
link varchar(128),
author_id int unsigned,
description text(512),
type_id int unsigned,
tag_id int unsigned,
denomination_id int unsigned,
Resource_date timestamp,
favorites int unsigned,
views int unsigned,
parent_org_id int unsigned,
language_id int unsigned,
is_free boolean,
instrument_type_id int unsigned,
topic_id int unsigned,
ensemble_id int unsigned,
ethnicity_id int unsigned,
hymn_soc_member_included boolean,
FOREIGN KEY (author_id) REFERENCES Authors(id),
FOREIGN KEY (type_id) REFERENCES Resource_Types(id),
FOREIGN KEY (tag_id) REFERENCES Resource_Tags(id),
FOREIGN KEY (denomination_id) REFERENCES Denominations(id),
FOREIGN KEY (parent_org_id) REFERENCES Parent_Org(id),
FOREIGN KEY (language_id) REFERENCES Languages(id),
FOREIGN KEY (instrument_type_id) REFERENCES Instrument_Types(id),
FOREIGN KEY (topic_id) REFERENCES Topics(id),
FOREIGN KEY (ensemble_id) REFERENCES Ensembles(id),
FOREIGN KEY (ethnicity_id) REFERENCES Ethnicities(id)
);
/* now for users and quizes */
CREATE TABLE users (
user_id int unsigned not null auto_increment,
email varchar(128) default null,
password varchar(128) default null,
first_name varchar(64) default null,
last_name varchar(64) default null,
reg_date timestamp,
is_active tinyint(1) default 1,
high_level tinyint(1) default 0,
PRIMARY KEY (user_id),
social_media_connections_id int unsigned not null,
FOREIGN KEY (social_media_connections_id) REFERENCES Social_Media_Connections(id)
);
CREATE TABLE quizes (
quiz_id int unsigned not null auto_increment,
quiz_title varchar(512),
is_active tinyint(1) default 1,
PRIMARY KEY (quiz_id)
);
CREATE TABLE questions (
question_id int unsigned not null auto_increment,
question_text varchar(512),
question_weight smallint unsigned default null,
PRIMARY KEY (question_id),
quiz_id int unsigned not null,
FOREIGN KEY (quiz_id) REFERENCES quizes (quiz_id)
);
CREATE TABLE tags (
tag_id int unsigned not null auto_increment,
tag_name varchar(128),
PRIMARY KEY (tag_id)
/* maybe link to other tables like congregation types? */
);
CREATE TABLE questions_choices (
choice_id int unsigned not null auto_increment,
choice_text varchar(512),
PRIMARY KEY (choice_id),
question_id int unsigned not null,
FOREIGN KEY (question_id)
REFERENCES questions (question_id),
/* after modification */
is_selected tinyint(1) default 0,
tag_id int unsigned not null,
FOREIGN KEY (tag_id)
REFERENCES tags (tag_id)
);
I have never designed a database of this size before so I am just looking for some input on what I have so far. I have a few questions as well:
Is it good practice to make separate tables to store different attributes?
Am I supposed to store password hashes instead of the actual passwords?
What is the most efficient way to map question_choices to users? I created a table called tags that should connect the two, then somehow use those tags to find different things in the table resource_tags to retrieve what interests the user.
Thanks

Related

MYSQL 1215 Cannot add Foreign Key Constraing

Problem is on the bounding table column GroupDim.FacultyID and FacultyDim.FacultyID, data types are identity BIGINT This data store for OLAP cube wherein Rating_facts stores result of question which i exploring. table without signature Dim is transitional and serve for additional data for analysis.Maybe it is needs to divide this table?
DROP TABLE IF EXISTS BlockDim;
CREATE TABLE BlockDim (
BlockKey bigint NOT NULL AUTO_INCREMENT,
BlockID bigint NOT NULL,
BlockName varchar(32) NOT NULL,
PRIMARY KEY (BlockKey)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS FacultyDim;
CREATE TABLE FacultyDim (
FacultyKey bigint NOT NULL AUTO_INCREMENT,
FacultyID bigint NOT NULL,
FacultyName varchar(32) NOT NULL,
PRIMARY KEY (FacultyKey, FacultyID)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS `Group`;
CREATE TABLE `Group` (
GroupID bigint NOT NULL,
FacultyID bigint NOT NULL,
GroupName varchar(32) NOT NULL,
PRIMARY KEY (GroupID),
FOREIGN KEY (FacultyID) REFERENCES FacultyDim(FacultyID)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS Subblock;
CREATE TABLE Subblock (
SubblockKey bigint NOT NULL AUTO_INCREMENT,
SubblockID bigint NOT NULL,
BlockID bigint NOT NULL,
SubblockName varchar(32) NOT NULL,
PRIMARY KEY (SubblockKey)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS Paragraph;
CREATE TABLE Paragraph (
ParagraphKey bigint NOT NULL AUTO_INCREMENT,
ParagraphID bigint NOT NULL,
SubblockID bigint NOT NULL,
ParagraphName varchar(64) NOT NULL,
PRIMARY KEY (ParagraphKey)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS RatingDim;
CREATE TABLE RatingDim (
RatingKey bigint NOT NULL AUTO_INCREMENT,
RatingID bigint NOT NULL,
ParagraphID bigint NOT NULL,
Score double NOT NULL,
StageOfApprove int NOT NULL,
Comment varchar(128) NOT NULL,
`Date` DATE NOT NULL,
PRIMARY KEY (RatingKey)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS TimeDim;
CREATE TABLE TimeDim (
TimeKey bigint NOT NULL AUTO_INCREMENT,
`Date` DATE NOT NULL,
DayOfWeek varchar(16) NOT NULL,
`Month` varchar(16) NOT NULL,
`Year` varchar(4) NOT NULL,
PRIMARY KEY (`TimeKey`)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS Rating_Fact;
CREATE TABLE Rating_Fact (
TimeKey bigint NOT NULL,
BlockKey bigint NOT NULL,
FacultyKey bigint NOT NULL,
RatingKey bigint NOT NULL,
PopularBlock bigint NOT NULL,
AvgFacultyScore bigint NOT NULL,
StudentsMaxRating bigint NOT NULL,
StudentsNotApprovedRating bigint NOT NULL,
PRIMARY KEY (TimeKey,BlockKey,FacultyKey,RatingKey),
FOREIGN KEY (TimeKey) REFERENCES TimeDim(TimeKey),
FOREIGN KEY (BlockKey) REFERENCES BlockDim(BlockKey),
FOREIGN KEY (FacultyKey) REFERENCES FacultyDim(FacultyKey),
FOREIGN KEY (RatingKey) REFERENCES RatingDim(RatingKey)
)ENGINE=InnoDB;
First you have check your table architecture.then try below two solutions
Solution 1:-
DROP TABLE IF EXISTS FacultyDim;
CREATE TABLE FacultyDim (
FacultyKey bigint NOT NULL AUTO_INCREMENT,
FacultyID bigint NOT NULL,
FacultyName varchar(32) NOT NULL,
PRIMARY KEY (FacultyKey, FacultyID)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS `Group`;
CREATE TABLE `Group` (
GroupID bigint NOT NULL,
FacultyID bigint NOT NULL,
GroupName varchar(32) NOT NULL,
PRIMARY KEY (GroupID),
FOREIGN KEY (FacultyID) REFERENCES FacultyDim(FacultyID,FacultyKey)
)ENGINE=InnoDB;
Solution 2:-
DROP TABLE IF EXISTS FacultyDim;
CREATE TABLE FacultyDim (
FacultyKey bigint NOT NULL AUTO_INCREMENT,
FacultyID bigint NOT NULL,
FacultyName varchar(32) NOT NULL,
PRIMARY KEY (FacultyID)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS `Group`;
CREATE TABLE `Group` (
GroupID bigint NOT NULL,
FacultyID bigint NOT NULL,
GroupName varchar(32) NOT NULL,
PRIMARY KEY (GroupID),
FOREIGN KEY (FacultyID) REFERENCES FacultyDim(FacultyID)
)ENGINE=InnoDB;

mysql - cannot add foreign key constraint when creating a table

I'm new to sql.
I get this error when I try to create foreign keys:
cannot add foreign key constraint
when I'm trying to create the ORDERS table. here is my code:
drop database if exists Company;
create database Company;
use Company;
create table WORKERS(w_id varchar(4), w_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique);
create table CUSTOMERS(customer_id varchar(4), customer_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique, credit bool);
create table WAREHOUSE(m_id int unsigned primary key, describes varchar(20) not null, fl char(1));
create table ITEM(p_id int(4) unsigned primary key, p_name varchar(15) not null, p_price float not null);
create table INVENTORY(in_id int auto_increment primary key, m_id int unsigned not null, p_id int(4) unsigned not null, amount int not null,
foreign key (m_id) references WAREHOUSE(m_id),
foreign key (p_id) references ITEM(p_id)
);
create table ORDERS(o_id int auto_increment primary key, customer_id varchar(4),
p_id int(4) unsigned, w_id varchar(4), amount int unsigned not null,
date_of_order date not null,
foreign key (p_id) references ITEM(p_id),
foreign key (w_id) references WORKERS(w_id),
foreign key (customer_id) references CUSTOMERS(customer_id)
);
I put the ORDERS (where I have the problem) on different lines to make it easier to you to read.
I search here for an answer, but didn't found anything specific that answer my question.
anyone got any idea what the problem is? thank you!
The problem is that you are trying to create a FOREIGN KEY relationship to a field in the WORKERS and CUSTOMERS tables that aren't set up as a PRIMARY KEY.
The FOREIGN KEY needs to be pointing to a PRIMARY KEY. Change your create script to the following:
create table WORKERS(w_id varchar(4) primary key, w_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique);
create table CUSTOMERS(customer_id varchar(4) primary key, customer_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique, credit bool);
A word of caution, though. I would recommend not using VARCHAR (4) as a PRIMARY KEY field. I would recommend using an INT AUTO_INCREMENT instead.
The column of the referenced table should be declared as primary key to assign a foreign key. For your orders table, WORKERS(w_id) and CUSTOMERS(customer_id) are not declared as primary key, hence you get the error.
Modified Statements:
drop database if exists Company;
create database Company;
use Company;
create table WORKERS(w_id varchar(4) primary key, w_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique);
create table CUSTOMERS(customer_id varchar(4) primary key, customer_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique, credit bool);
create table WAREHOUSE(m_id int unsigned primary key, describes varchar(20) not null, fl char(1));
create table ITEM(p_id int(4) unsigned primary key, p_name varchar(15) not null, p_price float not null);
create table INVENTORY(in_id int auto_increment primary key, m_id int unsigned not null, p_id int(4) unsigned not null, amount int not null,
foreign key (m_id) references WAREHOUSE(m_id),
foreign key (p_id) references ITEM(p_id)
);
create table ORDERS(o_id int auto_increment primary key, customer_id varchar(4),
p_id int(4) unsigned, w_id varchar(4), amount int unsigned not null,
date_of_order date not null,
foreign key (p_id) references ITEM(p_id),
foreign key (w_id) references WORKERS(w_id),
foreign key (customer_id) references CUSTOMERS(customer_id)
);
SQLFiddle Demo

MySQL Error 1217 [duplicate]

This question already has an answer here:
MySQL Error 1005?
(1 answer)
Closed 7 years ago.
I'm getting this error, and I know it's coming from the DROP TABLE IF statements, but I don't know how else to organize the drops for it to work. I've tried rearranging them but it won't work. The problem came when I introduced the Passenger table but I don't know how to fix it.
DROP TABLE IF EXISTS `Passenger`;
DROP TABLE IF EXISTS `ProductInvoice`;
DROP TABLE IF EXISTS `Invoice`;
DROP TABLE IF EXISTS `Product`;
DROP TABLE IF EXISTS `Customer`;
DROP TABLE IF EXISTS `Person`;
DROP TABLE IF EXISTS `Airport`;
DROP TABLE IF EXISTS `Address`;
DROP TABLE IF EXISTS `Email`;
CREATE TABLE Address
(
AddressID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AddressID),
AddressStreet VARCHAR(255),
AddressCity VARCHAR(255),
AddressState VARCHAR(255),
AddressZip VARCHAR(255),
AddressCountry VARCHAR(255)
);
CREATE TABLE Email
(
EmailID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(EmailID),
EmailAddress VARCHAR(255)
);
CREATE TABLE Person
(
PersonID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PersonID),
PersonCode VARCHAR(255),
PersonLastName VARCHAR(255),
PersonFirstName VARCHAR(255),
AddressID INT NOT NULL,
FOREIGN KEY `fk_Person_to_Address` (AddressID) REFERENCES Address(AddressID),
PersonPhone VARCHAR(255),
EmailID INT NOT NULL,
FOREIGN KEY `fk_Person_to_Email` (EmailID) REFERENCES Email(EmailID)
);
CREATE TABLE Airport
(
AirportID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AirportID),
AirportCode VARCHAR(255),
AirportName VARCHAR(255),
AddressID INT NOT NULL,
FOREIGN KEY `fk_Airport_to_Address` (AddressID) REFERENCES Address(AddressID),
AirportLatDeg INT NOT NULL,
AirportLatMin INT NOT NULL,
AirportLongDeg INT NOT NULL,
AirportLongMin INT NOT NULL,
AirportPassFacilityFee FLOAT NOT NULL
);
CREATE TABLE Customer
(
CustomerID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(CustomerID),
CustomerCode VARCHAR(255),
CustomerType VARCHAR(255),
PrimaryContact INT NOT NULL,
FOREIGN KEY `fk_Customer_to_Person` (PrimaryContact) REFERENCES Person(PersonID),
CustomerName VARCHAR(255),
CustomerAirlineMiles FLOAT NOT NULL
);
CREATE TABLE Product
(
ProductID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ProductID),
ProductCode VARCHAR(255),
ProductType VARCHAR(255),
DepAirportCode INT,
FOREIGN KEY `fk_Product_to_Airport` (DepAirportCode) REFERENCES Airport(AirportID),
ArrAirportCode INT,
FOREIGN KEY `frk_Product_to_Airport` (ArrAirportCode) REFERENCES Airport(AirportID),
DepartureTime VARCHAR(255),
ArrivalTime VARCHAR(255),
FlightNumber VARCHAR(255),
FlightClass VARCHAR(255),
AircraftType VARCHAR(255),
SeasonStartDate VARCHAR(255),
SeasonEndDate VARCHAR(255),
OffseasonRebate FLOAT,
AwardPointsPerMile FLOAT,
BaggageTicketCode INT,
FOREIGN KEY `fk_Product_to_Product` (BaggageTicketCode) REFERENCES Product(ProductID),
InsuranceName VARCHAR(255),
SpecialTypeOfService VARCHAR(255),
RefreshmentName VARCHAR(255),
RefreshmentCost FLOAT
);
CREATE TABLE Invoice
(
InvoiceID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(InvoiceID),
InvoiceCode VARCHAR(255),
CustomerCode INT NOT NULL,
FOREIGN KEY `fk_Invoice_to_Customer` (CustomerCode) REFERENCES Customer(CustomerID),
SalespersonCode INT NOT NULL,
FOREIGN KEY `fk_Invoice_to_Person` (SalespersonCode) REFERENCES Person(PersonID),
InvoiceDate VARCHAR(255)
);
CREATE TABLE ProductInvoice
(
ProductInvoiceID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ProductInvoiceID),
ProductID INT NOT NULL,
FOREIGN KEY `fk_ProductInvoice_to_Product` (ProductID) REFERENCES Product(ProductID),
InvoiceID INT NOT NULL,
FOREIGN KEY `fk_ProductInvoice_to_Invoice`(InvoiceID) REFERENCES Invoice(InvoiceID),
TravelDate VARCHAR(255),
NumOfPassengers INT NOT NULL,
Seat VARCHAR(255),
TicketNote VARCHAR(255)
);
CREATE TABLE Passenger
(
PassengerID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PassengerID),
PersonID INT NOT NULL,
FOREIGN KEY `fk_Passenger_to_Person` (PersonID) REFERENCES Person(PersonID),
IdentityNumber VARCHAR(255),
PassengerAge INT NOT NULL,
PassengerNationality VARCHAR(255),
ProductInvoiceID INT NOT NULL,
FOREIGN KEY `fk_Passenger_to_ProductInvoice` (ProductInvoiceID)
REFERENCES ProductInvoice(ProductInvoiceID)
);
This is the error I get:
Error Code: 1217. Cannot delete or update a parent row: a foreign key constraint fails
and it fails on the DROP TABLE for Invoice.
Disable foreign key checks or.
Drop the whole database or.
Run the script twice or.
Drop the fk constraints first.
Mysql workbench will generate a script for you if you highlight all if the tables and create a drop script. Same with the mysql dump utility.
How to temporarily disable a foreign key constraint in MySQL?

Problems with MYSQL Error 150 during table creation

I looked up other posts about this problem (there are a lot of them), but I have to say nothing worked so far for me. The only thing did not try was to disable foreign check.
My Problem:
When I try to create two simple tables I got the error 150 and I can't figure out why.
My Code so far:
drop table if exists SENSOR;
drop table if exists SENSOR_DATEN;
create table SENSOR (
SENSOR_ID int not null auto_increment,
SENSOR_NAME varchar(100),
SENSOR_POSX float not null,
SENSOR_POSY float not null,
SENSOR_EINHEIT varchar(100) not null,
primary key (SENSOR_ID)
);
commit;
create table SENSOR_DATEN (
SENSOR_DATEN_ID int not null auto_increment,
SENSOR_ID int not null,
SENSOR_DATEN_WERT varchar(100),
SENSOR_TYP varchar(100) not null,
primary key (SENSOR_DATEN_ID),
foreign key(SENSOR_ID) references SENSOR(SENSOR_ID),
foreign key(SENSOR_TYP) references SENSOR(SENSOR_EINHEIT)
);
commit;
My main problem is to understand the Problem. I got a way bigger database which is nearly identical but there are no problems. Here is the Code for the Database which works fine:
drop table if exists AUSGELIEHEN_FILM;
drop table if exists AUSGELIEHEN_SPIEL;
drop table if exists KUNDE;
drop table if exists FILM;
drop table if exists SPIEL;
create table KUNDE (
KUNDE_ID int not null auto_increment,
KUNDE_VNAME varchar(100),
KUNDE_NAME varchar(100),
KUNDE_ADRESSE varchar(100),
KUNDE_PLZ int not null,
primary key (KUNDE_ID)
);
create table FILM (
FILM_ID int not null auto_increment,
FILM_NAME varchar(100),
FILM_GENRE varchar(50),
FILM_FSK int not null,
FILM_BEWERTUNG int not null,
FILM_ANZAHL int not null,
FILM_MEDIUM varchar(50),
primary key (FILM_ID)
);
create table SPIEL (
SPIEL_ID int not null auto_increment,
SPIEL_NAME varchar(100),
SPIEL_GENRE varchar(50),
SPIEL_FSK int not null,
SPIEL_BEWERTUNG int not null,
SPIEL_ANZAHL int not null,
SPIEL_PLATFORM varchar(50),
primary key (SPIEL_ID)
);
create table AUSGELIEHEN_FILM (
AUSGELIEHEN_FILM_ID int not null auto_increment,
KUNDE_ID int not null,
FILM_ID int not null,
AUSGELIEHEN_ANZAHL int not null,
primary key(AUSGELIEHEN_FILM_ID),
foreign key(KUNDE_ID) references KUNDE(KUNDE_ID),
foreign key(FILM_ID) references FILM(FILM_ID)
);
create table AUSGELIEHEN_SPIEL(
AUSGELIEHEN_SPIEL_ID int not null auto_increment,
KUNDE_ID int not null,
SPIEL_ID int not null,
AUSGELIEHEN_ANZAHL int not null,
primary key(AUSGELIEHEN_SPIEL_ID),
foreign key(KUNDE_ID) references KUNDE(KUNDE_ID),
foreign key(SPIEL_ID) references SPIEL(SPIEL_ID)
);
commit;
Your table SENSOR_DATEN declares a foreign key that references SENSOR's column SENSOR_EINHEIT. This column is not defined as being unique, and thus can not have a foreign key pointing to it. Hence, your failure.
You could amend the declaration of SENSOR to make the column unique:
create table SENSOR (
SENSOR_ID int not null auto_increment,
SENSOR_NAME varchar(100),
SENSOR_POSX float not null,
SENSOR_POSY float not null,
SENSOR_EINHEIT varchar(100) not null,
primary key (SENSOR_ID),
unique (SENSOR_EINHEIT)
);
Or alternatively, apply it post-factum to an existing table:
alter table SENSOR add constraint SENSOR_EINHEIT_UNQ unique(SENSOR_EINHEIT);

mysql unable to add foreign key: error 1215 (hy000)

I am getting error 1215 (hy000): cannot add foreign key constraint then I run the following .sql file. The code below is also not creating the documents table, probably because it fails to create its foreign keys. Can anyone show me how to fix the code below so it will create the documents table including its foreign keys without throwing errors:
CREATE DATABASE IF NOT EXISTS petclinic;
GRANT ALL PRIVILEGES ON petclinic.* TO pc#localhost IDENTIFIED BY 'pc';
USE petclinic;
CREATE TABLE IF NOT EXISTS types (
id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(80),
INDEX(name)
) engine=InnoDB;
CREATE TABLE IF NOT EXISTS documenttypes (
id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(80),
INDEX(name)
) engine=InnoDB;
CREATE TABLE IF NOT EXISTS owners (
id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(30),
last_name VARCHAR(30),
address VARCHAR(255),
city VARCHAR(80),
telephone VARCHAR(20),
INDEX(last_name)
) engine=InnoDB;
CREATE TABLE IF NOT EXISTS pets (
id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
birth_date DATE,
type_id INT(4) UNSIGNED NOT NULL,
owner_id INT(4) UNSIGNED NOT NULL,
INDEX(name),
FOREIGN KEY (owner_id) REFERENCES owners(id),
FOREIGN KEY (type_id) REFERENCES types(id)
) engine=InnoDB;
CREATE TABLE IF NOT EXISTS documents (
id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
client_id int(4) NOT NULL,
type_id INT(4),
name varchar(200) NOT NULL,
description text NOT NULL,
filename varchar(200) NOT NULL,
content mediumblob NOT NULL,
content_type varchar(255) NOT NULL,
created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES owners(id),
FOREIGN KEY (type_id) REFERENCES documenttypes(id)
) engine=InnoDB;
I tried the advice at this link, but none of those suggestions work with this code. Can someone show me something that does work with this code?
The foreign key columns have to be the exact same data type as the original columns.
Try this:
CREATE TABLE IF NOT EXISTS documents (
id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
client_id int(4) UNSIGNED NOT NULL,
type_id INT(4) UNSIGNED NOT NULL,
name varchar(200) NOT NULL,
description text NOT NULL,
filename varchar(200) NOT NULL,
content mediumblob NOT NULL,
content_type varchar(255) NOT NULL,
created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES owners(id),
FOREIGN KEY (type_id) REFERENCES documenttypes(id)
) engine=InnoDB;
Added UNSIGNED to client_id and UNSIGNED NOT NULL to type_id (the NOT NULL part in is not mandatory though)
sqlfiddle demo