Foregin keys returns empty results - mysql

I'm using an a mySQL db on localhosts. Created table with primary key and another table with foreign key pointing to that one, but when I want to see the results all I geted is "alert" that MySQL returned emty result. Here my tables
CREATE TABLE example_1(
ex1_id int NOT NULL AUTO_INCREMENT,
first_name varchar(50) NULL,
last_name varchar(50) NULL,
CONSTRAINT example_1_pk PRIMARY KEY (ex1_id)
);
CREATE TABLE example_2 (
ex2_id int NOT NULL AUTO_INCREMENT,
acces_lvl int NOT NULL,
CONSTRAINT example_2_pk PRIMARY KEY (ex2_id)
);
CREATE TABLE example_3 (
ex3_id int NOT NULL AUTO_INCREMENT,
first int NOT NULL,
second int NOT NULL,
CONSTRAINT example_3_pk PRIMARY KEY (ex3_id),
FOREIGN KEY (first) REFERENCES example_1(ex1_id),
FOREIGN KEY (second) REFERENCES example_2(ex2_id)
);
Then I add something to db, eg.
INSERT INTO `example_1`(`first_name`, `last_name`) VALUES ('foo', 'bar');
and
INSERT INTO `example_2`(`acces_lvl`) VALUES (2)
then when I try
SELECT * FROM `example_3`
I have nothing, empty results. Shouldn't be there id's from other tables? Am I doing something wrong, or I didn't do something? I'm totally noob in database.

Because you did not insert any data into example_3. Foreign key constraints don't propagate data, they just enforce the data relationship, so when you do insert data into example_3, the values you put in the columns with foreign key constraints have corresponding values in other table.

Related

Not sure why this syntax error is happening

Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

Assign different muliple foreign key in one table from other table in MySQL

I was planning to make 2 tables for user infomation . The first lager table named userInfo has all data . The second smaller table named loginDetails have the minimum data to log in .
My problem is : I could not assign multiple foreign key .
MySQL said:
#1005 - Can't create table `test`.`logindetails` (errno: 150 "Foreign key constraint is incorrectly formed")
Here is code :
CREATE TABLE userInfo
(
userInfoUserNumber INT(255) UNSIGNED AUTO_INCREMENT UNIQUE NOT NULL,
userInfoUserName VARCHAR(255) UNIQUE NOT NULL,
userInfoPassword VARCHAR(255) NOT NULL,
userInfoFirstName VARCHAR(255) NOT NULL,
userInfoLastName VARCHAR(255) NOT NULL,
userInfoPhoneNumber INT(255) UNSIGNED ZEROFILL UNIQUE NOT NULL,
userInfoPlaceWithoutDivision VARCHAR(255) NOT NULL,
userInfoDivision VARCHAR(255) NOT NULL,
userInfoEmail VARCHAR(255) UNIQUE,
userInfoProfilePicture VARCHAR(255),
PRIMARY KEY (userInfoUserNumber)
);
CREATE TABLE loginDetails
(
loginDetailsUserNumber INT(255) UNSIGNED AUTO_INCREMENT UNIQUE NOT NULL,
loginDetailsUserName VARCHAR(255) UNIQUE NOT NULL,
loginDetailsPassword VARCHAR(255) NOT NULL,
loginDetailsPhoneNumber INT(255) UNSIGNED ZEROFILL UNIQUE NOT NULL,
loginDetailsEmail VARCHAR(255) UNIQUE,
PRIMARY KEY (loginDetailsUserNumber) ,
FOREIGN KEY (loginDetailsUserName) REFERENCES userInfo(userInfoUserName)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (loginDetailsPassword) REFERENCES userInfo(userInfoPassword)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (loginDetailsPhoneNumber) REFERENCES userInfo(userInfoPhoneNumber)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (loginDetailsEmail) REFERENCES userInfo(userInfoEmail)
ON DELETE SET NULL
ON UPDATE CASCADE
);
[ In short : suppose my first table has 10 columns , my second table has 5 columns , i want to choose any 4 columns from 1st table and copy to my second table ]
Question 2 :
why this statement is error ? please explain
INSERT INTO userInfo(userInfoUserName,userInfoPassword,userInfoFirstName,userInfoLastName,userInfoPhoneNumber,userInfoPlaceWithoutDivision,userInfoDivision)
VALUES (cat,SHA1(cat),white,cat,01111111111,myplace,mydivision);
You can declare a foreign key only if the column you reference is the leftmost column of a key.
Traditionally, you'd reference only a unique or primary key, but InnoDB (strangely) allows a foreign key to reference any kind of key or partial key.
Your column userInfo.userInfoPassword is not part of any key.
It's not clear what purpose there could be for declaring all those foreign keys. If you want them to cascade, to always remain the same value in the userInfo table, then why are they stored in both tables at all? Just store them in one table.
i want to create a different table (loginDetails) taking 4 columns from userinfo
Why? You don't have to create a different table if you want to fetch a result set with just those four columns. You just specify the columns you want in a query instead of using SELECT *.
SELECT loginDetailsUserNumber,
loginDetailsUserName,
loginDetailsPassword,
loginDetailsPhoneNumber,
loginDetailsEmail
FROM userInfo;
Another option would be to use CREATE VIEW to define a view with those four columns, and then you could use SELECT * from your view.
CREATE VIEW loginDetails AS
SELECT loginDetailsUserNumber,
loginDetailsUserName,
loginDetailsPassword,
loginDetailsPhoneNumber,
loginDetailsEmail
FROM userInfo;
SELECT * FROM loginDetails;
When designing foreign key relationships, you should be linking using primary keys. This would suggest:
CREATE TABLE loginDetails (
loginDetailsUserNumber INT UNSIGNED AUTO_INCREMENT UNIQUE NOT NULL,
loginDetailsUserInfoUserNumber INT UNSIGNED,
loginDetailsUserName VARCHAR(255) UNIQUE NOT NULL,
loginDetailsPassword VARCHAR(255) NOT NULL,
loginDetailsPhoneNumber INT(255) UNSIGNED ZEROFILL UNIQUE NOT NULL,
loginDetailsEmail VARCHAR(255) UNIQUE,
PRIMARY KEY (loginDetailsUserNumber) ,
FOREIGN KEY (loginDetailsUserInfoUserNumber) REFERENCES userInfo(userInfoUserNumber)
ON DELETE SET NULL
ON UPDATE CASCADE,
);
In other words, you can keep the duplicated columns (perhaps a user changes his/her name or password and you want the version associated with the login). BUT, you should be assigning a user number at login and putting that id in the table.

Cannot INSERT because of Foreign key constraints - mysql

So I don't understand why I cannot insert data in my table that have foreign constraint keys or even modify anything in it.
Here is an example of the tables that are created. I am trying to insert data in the addresses table:
///////////////////////ADDRESSES TABLE ////////////////////////
CREATE TABLE IF NOT EXISTS addresses (
id INT NOT NULL AUTO_INCREMENT,
addressline1 VARCHAR(255) NOT NULL,
addressline2 VARCHAR(255) NOT NULL,
postcode VARCHAR(255) NOT NULL,
phonenumber INT(13) NOT NULL,
country_id INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (country_id) REFERENCES countries(id)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE=InnoDB ";
///////////////////////COUNTRIES TABLE ////////////////////////
CREATE TABLE IF NOT EXISTS countries (
id INT NOT NULL AUTO_INCREMENT,
countryname VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
)
The issue here is that you are trying to insert into a referencing table (addresses) when the referenced entry (the country you reference) does not exist. That's what's triggering the FOREIGN KEY CONSTRAINT exception.
Try first inserting some countries into the countries table, then inserting some addresses where you reference those countries you entered in the first step.
As for your second question, that's a choice for you to make. I would probably choose to have the User have an Address (address field in the User table), but some of that depends on how the data is being used/updated.
Have a quick look through this resource if you're new to relational database design. It covers (in brief) topics like relationship types, key constraints, and normal forms.

Creation Failed: Key column 'name' doesn't exist in table:

I am trying to create a series of tables using Foreign Keys of Primary Keys from other tables, however I always get the error
Table Creation Failed: Key column 'PACId' doesn't exist in table:
Here is the first case it appears:
CREATE TABLE PlantAreaCodes(
PACId INT NOT NULL AUTO_INCREMENT,
AreaCode INT,
AreaName CHAR(32),
Comments TEXT,
PRIMARY KEY (PACId)
);
CREATE TABLE MajorEquipment(
MEId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (MEId),
FOREIGN KEY (PACId)
REFERENCES PlantAreaCodes(PACId)
);
Is it to do with the syntax of the foreign key, or is it because the PACId is still empty, and cannot be?
It is not that PACId is empty. You haven't declared it in MajorEquipment.
Try using this definition for the second table:
CREATE TABLE MajorEquipment(
MEId INT NOT NULL AUTO_INCREMENT,
PACId INT, -- Added this column
PRIMARY KEY (MEId),
FOREIGN KEY (PACId)
REFERENCES PlantAreaCodes(PACId)
);
Here is a SQL Fiddle.
Try this
CREATE TABLE MajorEquipment(
MEId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (MEId),
PACId INT
REFERENCES PlantAreaCodes(PACId)
)

How do I ensure that a foreign key exists as a primary key in another table when data is inserted?

This is an example of some tables that I'm using.
create TABLE People(
peopleID int not null,
name varchar(40) not null,
primary key (peopleID)
);
create table car(
carID int not null,
peopleID int not null,
primary key (carID),
foreign key (peopleID) references People(peopleID)
);
How do I ensure that when I insert into 'car', the 'peopleID' foreign key exists as a primary key in the table 'People'.
For example, I would want the following statement to throw an error:
INSERT INTO car VALUES (123, 343);
... because 343 doesn't exist in 'PeopleID', as it is empty.
Thanks
This is a bit long for a comment.
You have described what the foreign key constraint does:
For storage engines supporting foreign keys, MySQL rejects any INSERT
or UPDATE operation that attempts to create a foreign key value in a
child table if there is no a matching candidate key value in the
parent table.
The constraint is described here.