Creation of new table fails with error message "Foreign key constraint is incorrectly formed" - sql

I have 2 SQL statement as follows:
CREATE TABLE IF NOT EXISTS countries
(
country_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
country varchar(45) NOT NULL
);
CREATE TABLE IF NOT EXISTS patients
(
p_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
p_fname varchar(50) NOT NULL,
p_mname varchar(10) NULL,
p_lname varchar(50) NOT NULL,
age INT NOT NULL,
sex SET ('Male','Female'),
phone_num_mobile varchar(10) NULL,
phone_num_res varchar(7) NULL,
phone_num_office varchar(7) NULL,
email varchar(75) NULL,
addr_house varchar(10) NULL,
addr_street1 varchar(45) NOT NULL,
addr_street2 varchar(45) NULL,
addr_street3 varchar(45) NULL,
addr_city varchar(20) NOT NULL,
addr_country varchar(45) NOT NULL,
occupation varchar(20) NOT NULL,
married BOOLEAN NOT NULL,
FOREIGN KEY(addr_country) REFERENCES countries(country)
);
The first one executes successfully and the second one, which assigns a foreign key to the previous table, fails to execute with the message 'Foreign key constraint incorrectly formed'. I have also tried altering the second query's foreign key field(addr_country) to have the same name as that of the 'countries' table(country) but it were top no avail.
Can anyone please explain me what's going on and suggest me with a solution to this problem?
Thanks in advance.

A foreign key in MariaDB can only reference either a primary key in another table or a unique key. In this case, the countries table already has a primary key, so you can create a unique key on the country column.
Try putting a unique constraint on the country column in the countries table:
CREATE TABLE IF NOT EXISTS countries
(
country_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
country varchar(45) NOT NULL
UNIQUE KEY(country)
);
Late edit: As the commentors mentioned, you might want to just reference the country_id primary key instead of the country name. Since no two countries in the world have the same name, either might work in practice.

Related

"Syntax error in constraint clause" MS Access creating a table

I keep getting the syntax error in access when trying to add a foreign key to a table. The foreign key is LendorID and it is referenced in another table. What am I doing wrong?
Here is my code for creating the table:
CREATE TABLE BOOK_INVENTORY
(
CRN int NOT NULL PRIMARY KEY,
AuthorLastName varchar(20) NOT NULL,
AuthorFirstName varchar(20) NOT NULL,
BookTitle varchar (100) NOT NULL,
LendorID varchar(5) FOREIGN KEY REFERENCES LENDOR_INFO(LendorID),
);
Here is my code for the table that contains LendorID:
CREATE TABLE LENDOR_INFO
(
LendorID varchar(5) NOT NULL,
LendorLastName varchar(20) NOT NULL,
LendorFirstName varchar(20) NOT NULL,
LendorEmail varchar(100) NOT NULL,
PRIMARY KEY (LendorID)
);

Error in create table T-SQL "Incorrect syntax near ','."

When create table have error "Incorrect syntax near ','."
I cant see this error in code. Please point out this error.
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null,
quantity INT NOT null,
inventory_numbers INT NOT NULL PRIMARY KEY)
CREATE TABLE systematic_catalog(
id INT NOT NULL IDENTITY PRIMARY KEY,
udc_id INT FOREIGN KEY REFERENCES books(udc),
knowledge_area VARCHAR)
CREATE TABLE issued_books(
date_issued DATETIME,
inventory_numbers_id INT FOREIGN KEY REFERENCES books(inventory_numbers))
CREATE TABLE readers(
id INT NOT NULL IDENTITY PRIMARY KEY,
last_name VARCHAR CONSTRAINT,
first_name VARCHAR CONSTRAINT,
middle_name VARCHAR,
phone_number INT(11),
address VARCHAR,
ticket_number INT CONSTRAINT,
date_registration DATETIME,
date_reregistratiom DATETIME,
issued_books_id FOREIGN KEY REFERENCES issued_books(inventory_numbers_id))
You cannot add multiple primary keys to the table, either composite ey (combination of two fields) or Unique constraint can be added instead.
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null,
quantity INT NOT null,
inventory_numbers INT NOT NULL PRIMARY KEY)
this is an error, you cannot ass multiple primary keys. Instead you can add Unique constraint
Correction would be,
CREATE TABLE books(
id INT NOT NULL IDENTITY PRIMARY KEY,
author VARCHAR(150) NOT null,
date DATETIME NOT null,
city VARCHAR(50) NOT null,
publishing VARCHAR(50) NOT null,
udc INT NOT null Unique, --this is used to create the second table
quantity INT NOT null,
inventory_numbers INT NOT NULL Unique )
CREATE TABLE systematic_catalog(
id INT NOT NULL IDENTITY PRIMARY KEY,
udc_id INT FOREIGN KEY REFERENCES books(udc), --Referenced column needs to be unique
knowledge_area VARCHAR)
CREATE TABLE issued_books(
date_issued DATETIME,
inventory_numbers_id INT FOREIGN KEY REFERENCES books(inventory_numbers))
CREATE TABLE readers(
id INT NOT NULL IDENTITY PRIMARY KEY,
last_name VARCHAR (255),
first_name VARCHAR (255),
middle_name VARCHAR(255),
phone_number INT,
[address] VARCHAR(255),
ticket_number INT ,
date_registration DATETIME,
date_reregistratiom DATETIME)
You cannot use a foreign key of another table as a foreign key for some other table. You need to read more on table, Primary key constraints and foreign key referencing.
This cannot be done. you are trying to refer to the foreign key of issued_books table as a foreign key in readers table, which is wrong.
issued_books_id INT FOREIGN KEY REFERENCES issued_books(inventory_numbers_id))
I hope this explanation will give you a better understanding of errors. There were synatx errors as well as wrong use of the SQL table creation steps. I have added the corrected code for you. Feel free to contact any time.

How to select a common attribute from 2 different tables, with the highest appearence of a mutual attribute?

So i have a table "accident", and the attribute "pess_segura" which is the number of an ensured person envolved in an accidente.
I also have a table "acid_pess" which has 2 relevant attributes for this problem "accident" and "pessoa", this table refers to people envolved in accidents that are not ensured (they were involved in an accident but they were not driving).
So i want to select the accident with most people envolved.
These are the relevant tables for this exercise
create table person(
n_pess bigint not null,
nif integer not null,
cart_cond varchar(15),
pais_cart_cond varchar(30),
doc_id varchar(15) not null,
pais_doc_id varchar(30) not null,
nome varchar(80) not null,
primary key(n_pess),
unique(nif),
unique(cart_cond),
unique(doc_id)
);
create table ensurance(
apolice bigint not null,
ensured bigint not null,
veiculo bigint not null,
datai date not null,
dataf date not null,
cobertura numeric(10,2) not null,
primary key(apolice),
unique(ensured, veiculo),
foreign key (ensured) references person(n_pess),
foreign key (veiculo) references veiculo(n_veic)
);
create table accident(
n_acid bigint not null,
pess_segura bigint not null,
veic_seguro bigint not null,
data date not null,
local varchar(255) not null,
descr text not null,
primary key(n_acid),
unique(n_acid, veic_seguro),
foreign key (pess_segura,veic_seguro) references ensurance(ensured, veiculo)
);
create table acid_pess(
accident bigint not null,
person bigint not null,
veiculo bigint not null,
descr text not null,
primary key(accident, person),
foreign key (accident) references accident(n_acid),
foreign key (person) references person(n_pess),
foreign key (accident, veiculo) references accident(n_acid, veic_seguro)
);
I want to select the n_acid(number of the accident) that had the most people envolved.

What is breaking my sql program? Incorrect syntax near (

This code section
CREATE TABLE AIRPORT (
Airport_Code int NOT NULL,
City varchar(20) NOT NULL,
State varchar(20) NOT NULL,
Name varchar(25) NOT NULL,
CONSTRAINT PK_AIRPORT PRIMARY KEY (Airport_Code)
)
Is almost the same as this one but this one is giving me an error and I can't figure out how to fix it
CREATE TABLE AIRPLANE_TYPE (
Company varchar(20) NOT NULL,
Typename varchar(20) NOT NULL,
Max_seats int NOT NULL,
CONSTRAINT PK_AIRPLANE_TYPE (Typename) //error is here (Typename)
)
I am getting the error Incorrect syntax near '('.
Adding the primary key inline with the column will give you a crap auto-generated name for your primary key. I also don't understand how "encouraging primary keys to be on one column" is an added benefit.
CREATE TABLE AIRPLANE_TYPE (
Company varchar(20) NOT NULL,
Typename varchar(20) NOT NULL,
Max_seats int NOT NULL,
CONSTRAINT PK_AIRPLANE_TYPE PRIMARY KEY (Typename)
)
You are missing the PRIMARY KEY. I have a preference for putting this directly in the column definition:
CREATE TABLE AIRPLANE_TYPE (
Company varchar(20) NOT NULL,
Typename varchar(20) NOT NULL PRIMARY KEY,
Max_seats int NOT NULL
);
In addition to a shorter definition, this encourages all primary keys to be only one column -- an added benefit.

Type matches correctly, but why " #1215 - Cannot add foreign key constraint" keeps poping out?

This is my first table "address".
create table address(
street varchar(32) not null,
city varchar(32) not null,
state varchar(32) not null,
zip_code varchar(32) not null,
primary key(zip_code)
)
This is my second table "customer".
create table customer(
customer_id integer not null,
name varchar(32) not null,
primary key(customer_id)
)
This is my relational table about above two tables. But why cannot I make it? The type matches well. So please.
create table cus_live(
customer_id integer not null,
zip_code varchar(32) not null,
primary key(customer_id, zip_code),
foreign key(customer_id) references customer,
foreign key(zip_code) references address
)
This is the correct way to create a foreign key constraint:
create table cus_live(
cus_live_id int not null,
customer_id int not null,
address_id int not null,
primary key(cus_live_id),
foreign key(customer_id) references customer (customer_id),
foreign key(address_id) references address (address_id)
)
Notice the changes I made:
After references [tableName], added the key name in parentheses. This will tell SQL which column is referenced in the foreign key constrant.
Changed the primary key of the table to its own unique id rather than a composite of two columns. Usually this is better practice.
Changed primary key of address table to address_id instead of zipcode. Otherwise you would have conflicts if two customers have the same zipcode but different addresses within that zipcode.
Made your id's integers instead of strings.
Also, note that this is all assuming that cus_live has some other columns that you have excluded (and cannot be included on either the address or customer table) and hence warrants having this third table in the first place. Otherwise you could just put address_id on the customer table like this:
create table address(
address_id int not null,
street varchar(32) not null,
city varchar(32) not null,
state varchar(32) not null,
zip_code varchar(32) not null,
primary key(address_id)
)
create table customer(
customer_id int not null,
name varchar(32) not null,
address_id int not null,
primary key(customer_id)
foreign key(address_id) references address (address_id)
)