MySQL - Populate table column with values from another table - mysql

Need some help please. Creating a basic relational database and trying to add column values from my account table to my login table. However, bit stuck on how to achieve this. I'm trying to take the AccountID, Username, Sign_in data to populate the Login table but nothing appear when executed.
my code:
CREATE TABLE IF NOT EXISTS Account
(
AccountID int NOT NULL AUTO_INCREMENT,
Title VARCHAR(64) NOT NULL,
FirstName varchar(16) NOT NULL,
LastName varchar(32) NOT NULL,
DOB DATE,
Email VARCHAR(255),
Username varchar(32) UNIQUE NOT NULL,
Sign_in varchar(32) UNIQUE NOT NULL,
PRIMARY KEY (AccountID)
);
ALTER TABLE Account AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS Login
(
LoginID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
AccountID INT NOT NULL,
Username varchar(32) NOT NULL,
Sign_in varchar(32) NOT NULL,
LoginDate TIMESTAMP(6),
FOREIGN KEY (AccountID) REFERENCES Account(AccountID),
FOREIGN KEY (Username) REFERENCES Account(Username),
FOREIGN KEY (Sign_in) REFERENCES Account(Sign_in)
);
ALTER TABLE Login AUTO_INCREMENT=100;
and tried the query (edited from a similar query found on this forum) to no avail
INSERT INTO Login
(
AccountID,
Username,
Sign_in
)
SELECT
a.AccountID, a.Username, a.Sign_in
FROM Account a
INNER JOIN Login
ON a.AccountID = l.AccountID;
Select * from Login;
Help/advice appreciated.

You are missing the point of relational databases. You simply want to map to the primary key and then look up the other values. You don't want to store the values in two places.
So:
CREATE TABLE IF NOT EXISTS Account (
AccountID int AUTO_INCREMENT PRIMARY KEY,
Title VARCHAR(64) NOT NULL,
FirstName varchar(16) NOT NULL,
LastName varchar(32) NOT NULL,
DOB DATE,
Email VARCHAR(255),
Username varchar(32) UNIQUE NOT NULL,
Sign_in varchar(32) UNIQUE NOT NULL
);
CREATE TABLE IF NOT EXISTS Login (
LoginID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
AccountID INT NOT NULL,
LoginDate TIMESTAMP(6),
FOREIGN KEY (AccountID) REFERENCES Account(AccountID)
);
Then if you want the username or sign_in, you use a JOIN to look up that information.
I don't see a reason to set the auto-increment values. There is generally no problem having them start at 1 in all tables.

Managed to work it out...
INSERT INTO Login (AccountID, Username, Sign_in)
SELECT AccountID, Username, Sign_in
FROM Account;
Did take on board the advice regarding the Primary Key ID suggestion though. Cheers

Related

Unique Key on two table

is it possible to make two tables have a unique key like if my first table has the unique key and the second table cannot have the same text as the first table, it is possible to make that?
--
-- Table structure for table admin
DROP TABLE IF EXISTS admin;
CREATE TABLE IF NOT EXISTS admin (
ID varchar(11) NOT NULL,
Name varchar(100) NOT NULL,
Password varchar(100) NOT NULL,
Email varchar(100) NOT NULL,
PhoneNumber varchar(255) NOT NULL,
UniqueCode varchar(255) NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY UniqueCode (UniqueCode)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table admin
INSERT INTO admin (ID, Name, Password, Email, PhoneNumber, UniqueCode) VALUES
('AA11', 'Admin Low', '827ccb0eea8a706c4c34a16891f84e7b', 'AA11#gmail.com', '6012346778', 'Lmao'),
('AA12', 'Admin Tyler', '827ccb0eea8a706c4c34a16891f84e7b', 'AA11#gmail.com', '6033556778', 'Rofl');
--
-- Table structure for table lecturer
DROP TABLE IF EXISTS lecturer;
CREATE TABLE IF NOT EXISTS lecturer (
ID varchar(11) NOT NULL,
Name varchar(100) NOT NULL,
Password varchar(100) NOT NULL,
Email varchar(100) NOT NULL,
PhoneNumber varchar(255) NOT NULL,
UniqueCode varchar(255) NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY UniqueCode (UniqueCode)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table lecturer
INSERT INTO lecturer (ID, Name, Password, Email, PhoneNumber, UniqueCode) VALUES
('AL11', 'Cat Eat my son', '827ccb0eea8a706c4c34a16891f84e7b', 'AL11#gmail.com', '6012342222', 'Meow'),
('AL12', 'Dog Eat my son', '827ccb0eea8a706c4c34a16891f84e7b', 'AL12#gmail.com', '6033345678', 'Woof');
You can simply check before inserting data by useng "EXIST".
The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns TRUE if the subquery returns one or more records.
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);

MySQL AUTO_INCREMENT does not work: ER_NO_DEFAULT_FOR_FIELD: Field 'id' doesn't have a default value

CREATE TABLE User (
id int NOT NULL AUTO_INCREMENT,
username VARCHAR(20) NOT NULL,
email VARCHAR(40) NOT NULL,
image_file VARCHAR(40),
password VARCHAR(40) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE Post (
id int NOT NULL AUTO_INCREMENT,
date_posted DATE NOT NULL,
content VARCHAR(10000) NOT NULL,
user_id INT,
like_count INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE Post_comment (
id int NOT NULL AUTO_INCREMENT,
date_commented DATE NOT NULL,
content VARCHAR(10000) NOT NULL,
user_id INT,
like_count INT NOT NULL,
post_id INT,
PRIMARY KEY (id)
);
CREATE TABLE post_liked_by (
user_id int NOT NULL,
post_id int NOT NULL,
PRIMARY KEY (user_id,post_id)
);
CREATE TABLE comment_liked_by (
user_id int NOT NULL,
comment_id int NOT NULL,
PRIMARY KEY (user_id,comment_id)
);
ALTER TABLE User AUTO_INCREMENT=1;
ALTER TABLE Post
ADD FOREIGN KEY(user_id)
REFERENCES User(id)
ON DELETE SET NULL;
ALTER TABLE Post_comment
ADD FOREIGN KEY(user_id)
REFERENCES User(id)
ON DELETE SET NULL;
ALTER TABLE Post_comment
ADD FOREIGN KEY(post_id)
REFERENCES User(id)
ON DELETE SET NULL;
INSERT INTO User (username, email, password) VALUES ('egname', 'eg#eg.com', 'egpassword')
This code gives the error ER_NO_DEFAULT_FOR_FIELD: Field 'id' doesn't have a default value when I try to insert into the User table but I am not really sure why. I thought by setting AUTO_INCREMENT for the id field the default value would be 1? Could it be a problem with the configuration of my code editor? I am using PopSQL btw.
It works fine when I specify a value for id but I need it to increment automatically each time I insert a new data.
For context I am trying to build a simple project something like a clone of facebook. Tqvm in advance.

SQL that retrieves rows relative to its foreign keys in other tables

The problem is that I'm unsure if their exists a technical or standardized approach to what I'm trying to accomplish.
I've provided a basic approach that 'results' in the intended outcome, but I want to know if the foreign keys can be utilized inside the SQL to return the relative rows.
CREATE TABLE sessions(
SessionID INT(80) NOT NULL AUTO_INCREMENT,
Key VARCHAR(120) NOT NULL,
Username VARCHAR(25) NOT NULL,
Online VARCHAR(7) NOT NULL,
Status VARCHAR(10) NOT NULL,
IP VARCHAR(15) NOT NULL,
SocketID VARCHAR(20) NOT NULL,
Latest VARCHAR(20) NOT NULL,
Since VARCHAR(20) NOT NULL,
PRIMARY KEY (SessionID),
FORIEGN KEY (Username) REFERENCES users(Username)
)
CREATE TABLE Users(
UserID INT(80) NOT NULL AUTO_INCREMENT,
Username VARCHAR(25) NOT NULL,
Email VARCHAR(200) NOT NULL,
Password VARCHAR(255) NOT NULL,
FirstName VARCHAR(50),
LastName VARCHAR(50),
BirthDate VARCHAR(50),
RegistrationDate TIMESTAMP(20) NOT NULL DEFAULT CURRENT_TIMESTAMP
PRIMARY KEY (SessionID),
FORIEGN KEY (Username) REFERENCES friends(Sender, Reciever)
)
CREATE TABLE Friends(
FriendID INT(80) NOT NULL AUTO_INCREMENT,
Sender VARCHAR(25) NOT NULL,
Reciever VARCHAR(25) NOT NULL,
Status VARCHAR(10) NOT NULL,
Sent_Timestamp VARCHAR(16) NOT NULL,
Response_Timestamp VARCHAR(16),
PRIMARY KEY (FriendID),
FORIEGN KEY (Sender, Reciever) REFERENCES Users(Username)
)
"SELECT * FROM Sessions, Users, Friends WHERE Sessions.Username = Users.username AND Sessions.Username = Friends.Sender OR Session.Username = Friends.Reciever";
Now what SQL can I execute in order to return all the relative rows of a single row in the sessions table. Notice the ForiegnKey on the Username. Is it a combination of SELECT Statements that defines the relationship inside the SQL?
EG: SELECT * FROM Sessions, Users, Friends WHERE Sessions.Username = Users.username AND Sessions.Username = Friends.Sender OR Session.Username = Friends.Reciever";
Or does SQL have a function that can interpretate the relationship between the foreign keys and return all the relate-able and relevant results with a more sophisticated SQL query? Or is my previous SQL statement the correct approach?

How add a customer to an order when getting the customer details from a form

I am having trouble adding a customer and their order to an order table once they have checked out.
Here is my SQL for creating the four tables I am using:
CREATE TABLE IF NOT EXISTS Product(
ID int NOT NULL AUTO_INCREMENT,
Name varchar(255) NOT NULL,
Description text(65535) NOT NULL,
Quantity int NOT NULL,
Photo varchar(255),
Price float NOT NULL,
Category varchar(50),
PRIMARY KEY (ID)
) ENGINE=innoDB;
CREATE TABLE IF NOT EXISTS Customer(
ID int NOT NULL AUTO_INCREMENT,
FirstName varchar(255) NOT NULL,
LastName varchar(255) NOT NULL,
Email varchar(255) NOT NULL,
PhoneNumber varchar(11) NOT NULL,
Address varchar(50),
Town varchar(50),
County varchar(50),
PostCode varchar(50),
PRIMARY KEY (ID)
) ENGINE=innoDB;
CREATE TABLE IF NOT EXISTS OrderTable(
ID int NOT NULL AUTO_INCREMENT,
Date date NOT NULL,
PRIMARY KEY (ID),
TotalPrice float NOT NULL,
Customer_ID int NOT NULL,
CONSTRAINT fk_Order_1
FOREIGN KEY (Customer_ID)
REFERENCES coursework_db.Customer (ID)
) ENGINE=innoDB;
CREATE TABLE IF NOT EXISTS OrderItem(
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (ID),
Product_ID int NOT NULL,
Order_ID int NOT NULL,
Quantity int NOT NULL,
TotalPrice float NOT NULL,
CONSTRAINT fk_OrderItem_1
FOREIGN KEY (Product_ID)
REFERENCES coursework_db.Product(ID),
CONSTRAINT fk_OrderItem_2
FOREIGN KEY (Order_ID)
REFERENCES coursework_db.OrderTable(ID)
) ENGINE=innoDB;
The problem I am having is how to select the customer from the table once they have been added to the database to use as a foreign key in the OrderTable table.
At the moment I have the details of the customer stored in local storage which can easily be accessed, but once the customer is added to the database they will get an ID. This is the only way I could think to select a unique customer.
Insert the customer details first. Then get the ID of the newly inserted customer and use it while inserting the order details!
You could use the LAST_INSERT_ID() after you insert the user details to the db to get the ID of the customer.
Or if you are using PHP, then:
if you're using PDO, use PDO::lastInsertId
if you're using Mysqli, use mysqli::$insert_id
Hope this helps.

MySQL advise on building a database with connected tables

I want to build a database which holds information about users in a table:
User
-username (primary key)
-first_name
-second_name
-Image
In this database there will be another table like so:
Image
-name (primary key)
-file_name
What I want to achieve
I want each user to have Image as one of its fields. I understand to do this I have to connect the tables.
What I know so far
Firstly I should define the tables as InnoDB, then using phpmyadmin click on relationView.
The Question
How do I achieve the relationship I described above using phpmyadmin?
If a user have only one image it is one to one relationship. Everything can do with a one table.
Something like this:
CREATE TABLE users (
userId INT UNSIGNED NOT NULL AUTO_INCREMENT,
userFirstName VARCHAR(80) NOT NULL,
userSecondName VARCHAR(80),
imageName VARCHAR(100) NOT NULL,
PRIMARY KEY (userId)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Multiple images have to one user, there is a one to many relationship. So you can create two tables and one lookup table.
Like this:
CREATE TABLE users (
userId INT UNSIGNED NOT NULL AUTO_INCREMENT,
userFirstName VARCHAR(80) NOT NULL,
userSecondName VARCHAR(80),
imageName VARCHAR(100) NOT NULL,
PRIMARY KEY (userId)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE images (
imageId INT UNSIGNED NOT NULL AUTO_INCREMENT,
imageName VARCHAR(100) NOT NULL,
PRIMARY KEY (imageId)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Lookup table:
CREATE TABLE user_image (
userId INT UNSIGNED,
imageId INT UNSIGNED
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
You should put a column on table Image that will be reference on the table User, if for intance, a user can have multiple images. ex,
User
username (primary key)
first_name
second_name
Image
name (primary key)
file_name
userName (Foreign Key)
translated into DDL:
CREATE TABLE `User`
(
userName VARCHAR(15),
first_name VARCHAR(15),
second_name VARCHAR(15),
CONSTRAINT tb_pk PRIMARY KEY (userName),
CONSTRAINT tb_uq UNIQUE (first_name, last_name)
);
CREATE TABLE `Image`
(
name VARCHAR(15),
file_name VARCHAR(75),
userName VARCHAR(15)
CONSTRAINT tb_pk PRIMARY KEY (name),
CONSTRAINT tb_fk FOREIGN KEY (userName) REFERENCES `User`(userName)
);