Below is a portion of relational data base. I know how to create table Film and assign primary key to it.. but don't understate creating other tables and assigning primary key to it.
Any help?
table Film
CREATE TABLE Film (
Id INTEGER PRIMARY KEY,
Title VARCHAR(35) NOT NULL,
Description VARCHAR(256) NOT NULL,
Year INTEGER NOT NULL CHECK (Year > 1900),
Rating INTEGER NOT NULL DEFAULT 3 CHECK (Rating BETWEEN 1 AND 5)
);
how do I create table FilmFormat and OrderItem ?
CREATE TABLE `jy` (
`PKfield` INTEGER UNSIGNED NOT NULL DEFAULT NULL AUTO_INCREMENT,
`field2` VARCHAR(45) NOT NULL,
PRIMARY KEY (`PKfield`),
CONSTRAINT `FK` FOREIGN KEY `FK` (`PKfield`)
REFERENCES `Film` (`Id`)
ON DELETE RESTRICT
ON UPDATE RESTRICT
)
ENGINE = InnoDB;
This is enough to show you how to create a foreign key constraint between the two tables. As commented, the CHECK constraint will be parsed but ignored.
CREATE TABLE Film (
Id INTEGER PRIMARY KEY,
Title VARCHAR(35) NOT NULL,
Description VARCHAR(256) NOT NULL,
Year INTEGER NOT NULL CHECK (Year > 1900),
Rating INTEGER NOT NULL DEFAULT 3 CHECK (Rating BETWEEN 1 AND 5)
);
CREATE TABLE FilmFormat (
FilmId INTEGER not null,
FormatId INTEGER not null,
Price decimal(16,4) null,
Primary Key(FilmId, FormatId),
Constraint FK_FilmFormat_FilmId FOREIGN KEY (FilmId) REFERENCES Film(Id)
);
Doing the last table will just be doing your work for you.
Related
I have the following SQLite3 database
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
email VARCHAR(75) NOT NULL,
password VARCHAR(128) NOT NULL
);
CREATE TABLE IF NOT EXISTS pads (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(100) NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id)
);
CREATE TABLE notes (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
pad_id INTEGER REFERENCES pads(id),
user_id INTEGER NOT NULL REFERENCES users(id),
name VARCHAR(100) NOT NULL,
text text NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
~
I have tried to migrate this sql schema to mysql and postgres, everything seems to be working fine except for one detail.
The table notes should accept pad_id as NULL, if there is no pad a note should be saved but when I try to save a note without a pad I get an error
sqlalchemy.exc.IntegrityError
IntegrityError: (psycopg2.errors.ForeignKeyViolation) insert or update
on table "note" violates foreign key constraint "note_pad_id_fkey"
DETAIL: Key (pad_id)=(0) is not present in table "pad".
But I should be able to save it as NULL, it works fine on SQLite3.
What should I change to be able to accomplish this?
Thank you.
Neither MySQL nor Postgres has a problem, with NULL as padod see examples
Therefore the error messahe comes from postgres, but it is because of the migration
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
email VARCHAR(75) NOT NULL,
password VARCHAR(128) NOT NULL
);
CREATE TABLE IF NOT EXISTS pads (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
name VARCHAR(100) NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id)
);
CREATE TABLE notes (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
pad_id INTEGER REFERENCES pads(id),
user_id INTEGER NOT NULL REFERENCES users(id),
name VARCHAR(100) NOT NULL,
`text` text NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
INSERT INTO users VALUES(NULL,'test','pass')
✓
INSERT INTO notes VALUES (NULL,NULL,1,'test','text',NOW(),NOW())
✓
db<>fiddle here
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY NOT NULL,
email VARCHAR(75) NOT NULL,
password VARCHAR(128) NOT NULL
);
CREATE TABLE IF NOT EXISTS pads (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(100) NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id)
);
CREATE TABLE notes (
id SERIAL PRIMARY KEY NOT NULL,
pad_id INTEGER REFERENCES pads(id),
user_id INTEGER NOT NULL REFERENCES users(id),
name VARCHAR(100) NOT NULL,
"text" text NOT NULL,
created_at timestamp NOT NULL,
updated_at timestamp NOT NULL
);
INSERT INTO users VALUES(DEFAULT,'test','pass')
1 rows affected
INSERT INTO notes VALUES (DEFAULT,NULL,1,'test','text',NOW(),NOW())
1 rows affected
db<>fiddle here
I have 3 table
CREATE TABLE tag (
name VARCHAR(294) NOT NULL,
inserted_at DATETIME NOT NULL,
status INTEGER NOT NULL,
PRIMARY KEY (name)
) Engine=innoDB;
CREATE TABLE item (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(294) NOT NULL,
price INTEGER NOT NULL,
discounted_price INTEGER DEFAULT NULL,
unit VARCHAR(294) NOT NULL,
additional_message TEXT NOT NULL,
stock INTEGER NOT NULL,
is_featured INTEGER NOT NULL,
inserted_at DATETIME NOT NULL,
status INTEGER NOT NULL,
PRIMARY KEY (id)
) Engine=innoDB;
ALTER TABLE item ADD FULLTEXT(name, additional_message);
CREATE TABLE item_tag (
id INTEGER NOT NULL AUTO_INCREMENT,
item_id INTEGER NOT NULL,
tag_name VARCHAR(294) NOT NULL,
inserted_at DATETIME NOT NULL,
status INTEGER NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (tag_name) REFERENCES tag(name),
FOREIGN KEY (item_id) REFERENCES item(id)
) Engine=innoDB;
ALTER TABLE item_tag ADD FULLTEXT(tag_name);
The first Alter Command works perfectly, but the second does not. It return #1215 - Cannot add foreign key constraint.
Do you know why?, or better, how to fix it ?
As far as I know you cannot have MySQL 5.5 does not support FullText and Foreign key constraint together on the same. You can create either of them to get it working.
I will try to be specific because I feel my understanding of the subject isn't quite precise as well. My problem is understanding how to create relations between tables with foreign keys which I add with alter statements. I have these tables.
CREATE TABLE article (
content TEXT NOT NULL,
published_on DATE NOT NULL,
created_on DATE NOT NULL,
);
CREATE TABLE category(
name VARCHAR(30) NOT NULL,
date_created DATE NOT NULL,
);
CREATE TABLE user(
income FLOAT(30, 30) NOT NULL,
password VARCHAR(30) NOT NULL,
picture_url TEXT NOT NULL,
);
CREATE TABLE tag(
description VARCHAR(30) NOT NULL,
second_priority FLOAT(30, 30) NOT NULL,
);
To which I have to make there relationships:
Tag has a one to one connection to Category
Category has a many to one connection to User
User has a one to many connection to Article
And to do that I use there statements:
ALTER TABLE tag ADD CONSTRAINT FOREIGN KEY (tag_id) REFERENCES category (category_id);
ALTER TABLE category ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (user_id);
ALTER TABLE user ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES article (user_id);
My problem is that the third one fails. When I switch the places of article and user the constraint passes. After a bit of digging and experimenting I found out that I can't constraint two keys from which one is either UNIQUE or PRIMARY KEY and the other one just NOT NULL. So far I don't know how to continue, can someone please enlighten me as to how to create a one to one, many to one, one to many and a many to many relationship between these tables because I am kinda lost and everything in my head is a mess.
FULL STUFF:
CREATE DATABASE exam_database;
USE exam_database;
CREATE TABLE article (
content TEXT NOT NULL,
published_on DATE NOT NULL,
created_on DATE NOT NULL,
user_id INT(30) NOT NULL
);
CREATE TABLE category(
name VARCHAR(30) NOT NULL,
date_created DATE NOT NULL,
category_id INT(30) NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
user_id INT(30) NOT NULL
);
CREATE TABLE user(
income FLOAT(30, 30) NOT NULL,
password VARCHAR(30) NOT NULL,
picture_url TEXT NOT NULL,
user_id INT(30) NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE
);
CREATE TABLE tag(
description VARCHAR(30) NOT NULL,
second_priority FLOAT(30, 30) NOT NULL,
tag_id INT(30) NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE
);
ALTER TABLE tag ADD CONSTRAINT FOREIGN KEY (tag_id) REFERENCES category (category_id);
ALTER TABLE category ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (user_id);
ALTER TABLE user ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES article (user_id);
First Your structure has some errors:
Missing PK, Why using INT(30)? etc...
Your DB should looks like:
CREATE DATABASE exam_database;
USE exam_database;
CREATE TABLE article (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
user_id INT NOT NULL,
content TEXT NOT NULL,
published_on DATE NOT NULL,
created_on DATE NOT NULL
);
CREATE TABLE category(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
user_id INT NOT NULL,
name VARCHAR(30) NOT NULL,
date_created DATE NOT NULL
);
CREATE TABLE user (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE ,
income FLOAT(30, 30) NOT NULL,
password VARCHAR(30) NOT NULL,
picture_url TEXT NOT NULL
);
CREATE TABLE tag (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
category_id INT NOT NULL,
description VARCHAR(30) NOT NULL,
second_priority FLOAT(30, 30) NOT NULL
);
Second Your FKs should look like:
ALTER TABLE tag ADD CONSTRAINT FOREIGN KEY (category_id) REFERENCES category (id);
ALTER TABLE category ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (id);
ALTER TABLE article ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (id);
I have the following 3 tables
CREATE TABLE BUBBLES_CSC (
CSC_ID integer UNSIGNED NOT NULL AUTO_INCREMENT,
COUNTRY_NAME varchar(255) NOT NULL,
STATE_NAME varchar(255) NOT NULL,
CITY_NAME varchar(255) NOT NULL,
PRIMARY KEY(CSC_ID,STATE_NAME,CITY_NAME),
INDEX(CSC_ID ,CITY_NAME,COUNTRY_NAME )
);
CREATE TABLE BUBBLES_REGION (
REGION_ID integer UNSIGNED NOT NULL AUTO_INCREMENT,
REGION_NAME varchar(255) NOT NULL,
CSC_ID integer UNSIGNED NOT NULL,
PRIMARY KEY(REGION_ID),
FOREIGN KEY (CSC_ID) REFERENCES BUBBLES_CSC(CSC_ID) ON UPDATE CASCADE ON DELETE CASCADE,
INDEX(REGION_ID ,REGION_NAME ,CSC_ID )
);
CREATE TABLE BUBBLES_HOTEL (
HOTEL_ID integer UNSIGNED NOT NULL AUTO_INCREMENT,
NAME varchar(255) NOT NULL,
DESCRIPTION varchar(255) DEFAULT "No description",
CSC_ID integer UNSIGNED NOT NULL,
REGION_ID integer UNSIGNED NOT NULL,
STREET_ADDRESS varchar(255) DEFAULT NULL,
PRIMARY KEY(HOTEL_ID),
FOREIGN KEY (CSC_ID) REFERENCES BUBBLES_CSC(CSC_ID) ON UPDATE CASCADE,
FOREIGN KEY (REGION_ID) REFERENCES BUBBLES_REGION(REGION_ID) ON UPDATE CASCADE,
INDEX(HOTEL_ID,NAME,CSC_ID,REGION_ID)
)CHARACTER SET=utf8;
Now i know how to do a foreign key, But how to specify that the CSC_ID in BUBBLES_HOTEL should be same as the CSC_ID specified in BUBBLES_REGION for the row pointed to by REGION_ID in BUBBLES_HOTEL
The proper way to do this is not to have the column CSC_ID in BUBBLES_HOTEL at all. Each row in BUBBLES_HOTEL contains a link to a row in BUBBLES_REGION, which in turn contains a link to a row in BUBBLES_CSC. That's how you identify to which row in BUBBLES_CSC a given row in BUBBLES_HOTEL corresponds. Your current design is not normalised.
Having said that, you could achieve what you ask by replacing the two foreign keys on BUBBLES_HOTEL with just one:
FOREIGN KEY (CSC_ID, REGION_ID) REFERENCES BUBBLES_REGION (CSC_ID, REGION_ID)
I assume that all three relations create one-to-one-to-one chain. If so, you should not have the CSC_ID column in BUBBLES_HOTEL, it is redundant: you always can get it via BUBBLES_REGION.
I am wanting to have a label column (VARCHAR) and I want it to be unique, but when I try to create the table it seems to be throwing an error. Can a unique constraint only be used in conjunction with an INTEGER or will it work with other datatypes as well. The error I am getting is (ERRNO 150)
CREATE TABLE IF NOT EXISTS `user`(
user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
`password` VARCHAR(255) NOT NULL
);
CREATE TABLE IF NOT EXISTS `element`(
element_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
label VARCHAR(5) NOT NULL DEFAULT '',
parent_id INT NULL,
user_id INT NOT NULL,
created_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
edited_on TIMESTAMP NOT NULL,
UNIQUE(label),
KEY element_1 (label),
CONSTRAINT FK_element_1 FOREIGN KEY (user_id) REFERENCES `user` (user_id),
CONSTRAINT FK_element_2 FOREIGN KEY (parent_id) REFERENCES `element` (element_id)
);
The only way I can have this error, if the first table is created with MyISAM engine and the second (tried to be created) with InnoDB.
Check the definition of the created table user, using:
SHOW CREATE TABLE user ;
If that's the case, drop it and recreate it with:
CREATE TABLE IF NOT EXISTS `user`(
user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
`password` VARCHAR(255) NOT NULL
)
ENGINE = InnoDB ;