How can i join another table with the primary of the other - mysql

I am creating an application like trello for that i am using MySQL as an database till now i have created authentication system using MySQL and express,node js now i want to create table for cards to save the data so, i want to know how can i link the users data to the users name.
I have created a table users with the following field id(primary key, auto_increment),name,email,password
now i want to create a table card in which the users card would be present so how can i link user table column correspond to the particular
use, thanks in advance really new to backed

Maybe this lines of code can help you out a little. To get a better grasp of the topic.
-- This statement creates the cards table you may want to use (alternatively see Barmars Comment, this maybe a more professional solution)
CREATE TABLE Cards (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
customer_id INT,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50)
)
-- This statement then "connects" the tables. It makes the customer_id in the cards table a foreign key of the primary key of the customers table.
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
After implementing this you can use JOIN in your queries to query multiple tables.
If you want more info, this video can help you understand the topic:
https://www.youtube.com/watch?v=USaXlErI-QE

Related

How to structure my database model for a simple web application and organize my SQL data model

I am working on a web app. I have a question about the SQL parts. I am currently creating a food rating interface. The user should be able to login and then rate the food.
Currently I use a custom database (users) for the login page. I also use a separate database (review) for the reviews. my current database structure makes no sense.
In the attached image you can see the tables, they are currently separate databases with only this one table each. I use MySQL extension in VSCode.
How can I combine the tables into one database? I am looking for some ideas for this problem.
Preferably the username should only be needed for login and not have to be entered separately in the rating (as unfortunately still current).
In the future, the user should be directed after login, to a page where he can select his dish, then he should rate it. Each dish should save the ratings individually, to distinguish this of course.
I suggest that you do use the user table as a reference for reviews, and also a table dish with the details of each dish.
Here are suggested table definitions, to fine-tune to your needs:
Credits to Mishi for the improvement to foreign key syntax to make it more portable.
I've put the creation of the table review last because some SQL engines check that the table exists when we declare a foreign key.
create table users
(
uid int primary key,
username varchar(25),
password varchar(25),
created_at date
);
create table dish
(
did int primary key,
nom varchar(25),
description varchar(250),
last_rating int
);
create table review
(
rid int primary key,
user_id int ,
dish_id int ,
user_rating int ,
user_reveiw varchar(100),
review_date datetime,
foreign key (user_id) references users(uid),
foreign key (dish_id) references dish(did)
);
db<>fiddle here

What decides what constrains to use when creating table from a physical schema

I am learning SQL and going trough some lab exercises when i got to a question that asks to create table from a physical schema. No problem there, simple enough to create a table, but i got it wrong because i didn't use the NOT NULL, NULL, and FKconstraints. So what in this schema tells me what constrains to use? Here is the correct answer according to the exercise. (the auto increment was provided in the question)
CREATE TABLE customerorder (DonutOrderID INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
CustomerID INT(11) NOT NULL,
DonutOrderTimestamp TIMESTAMP DEFAULT NOW(),
SpecialNotes VARCHAR(500) NULL,
FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID));
A customerorder without a customer makes no sense, so its customer ID column should not be nullable.
A customerorder must refer to an existing customer, so you should make the customer ID a foreign key to the customer table.
SpecialNotes are only special when they are optional in my opinion, so the should be nullable.
If the table is called customerorder, its ID should not be called DonutOrderID, as this name looks somewhat unrelated and I'd expect some additional DonutOrder table in the database. The customerorder's ID should be called id or customerorder_id or the like instead.
As a customer order seems to be a donat order in that database, the DonutOrderTimestamp should probably be obligatory (i.e. not nullable), as every order is placed at some point in time.

How to design mysql tables that follow multiple values from each other

I am trying to make something of a vacation website where a user can follow certain vacations.
Right now there are 2 tables, one for vacations and one for users.
I want to make it so when a user decides to follow a vacation, it will be somehow associated with him like a column of "followedVacations" that would contain the ids of the vacations he's following.
Problem is what if he is following multiple vacations? how do i store that information with the user, or alternatively store on the vacation entry which users are following it?
I am using mysql, react and node if that has any relevancy
I don't know how to make it work so i couldn't really try anything
iv'e got no code to show because i dont know how to approach this on a table and schema design level
I'm basically looking for the correct way to do this.
Edit: Would it be possible to also have amount of followers on the vacation table?
A standard approach here would be to create a third junction table which relates users to vacations and vice-versa. So, you might have the following three tables:
CREATE TABLE users (
id INT NOT NULL,
name VARCHAR(50),
PRIMARY KEY(id)
)
CREATE TABLE vacations (
id INT NOT NULL,
name VARCHAR(50),
location VARCHAR(50),
price DECIMAL(10,2),
PRIMARY KEY (id)
)
CREATE TABLE user_vacations (
user_id INT NOT NULL,
vacation_id INT NOT NULL,
PRIMARY KEY (user_id, vacation_id)
)
Note that the junction user_vacations table mainly exists to relate users to vacations. All the metadata associated with a user or vacation would continue to be stored in your current two tables which already exist.

Relationships midst two tables?

I have table visitors and table users. Each visitor can be created by only one user and contains field visitors.userId.
So, any another user from table users can edit or delete one or more visitors.
I have created a third table events_log for logging actions like edit/delete:
Visitors_log
id | userId | visitorId | action
This table stores information about user who did actions over table visitors.
Which relationship should be between table visitors_log and rest two: users and visitors?
Now I have this Db scheme:
My opinion is: visitors_log can have one or more rows. So relations is one to many. In the same time visitors_log can contain one or more users. So, where I am wrong? Now it is one to one relation.
Is there a possibility that the user_id of a visitor could ever change ?
If the answer is yes, then you would better take the safe approach and have two foreign keys in the log, referencing the concerned visitor and the user that commited the action.
In MySQL :
CREATE TABLE visitors_log (
idVisitorLog INT AUTO_INCREMENT,
idVisitor INT NOT NULL,
idUser INT NOT NULL,
action VARCHAR(100) NOT NULL,
date_action DATETIME NOT NULL,
PRIMARY KEY (idVisitorLog),
FOREIGN KEY (visitor_log_idVisitor) REFERENCES visitors(idVisitor),
FOREIGN KEY (visitor_log_idUser) REFERENCES users(idUser)
);
PS : you probably want a date column too in the log table, I added one.
On the other hand, if the user a visitor is assigned to can never change over time, then your design can be simplified. In the log table, you could just store a foreign key to the visitors table. As the visitor stores a (fixed) user id, you do not need to duplicate that information in the log.

Insert Data into multiple tables in MySQL

Consider two tables User and UserDetails
User (UserID,Name,Password)
UserDetails(UserID,FullName, Mobile Number,EMail)
First I will enter details into User table
Then Afterwards I wish to enter details into UserDetails Table with respect to primary key of first table i.e., UserID which is autoincremented.
consider this scenario..
User: (101, abc, xyz), (102,asd,war)
Now i want to store details in second table with respect to Primary key where UserID= 102
How can I accomplish this?
Start over with the design. Here is a start that runs through and doesn't blow up. Do the same for email. Keep data normalized and don't cause unnecessary lookups. When you have a lot of constraints, it is a sign that you care about the quality of your data. Not that you don't without constraints, if they are un-constrainable.
We all read on the internet how we should keep main info in one table and details in another. Nice as a broad brush stroke. But yours does not rise to that level. Yours would have way too many tables. See Note1 at bottom about about Entities. See Note2 at bottom about performance. See any of us with any broad or specific question you may have.
create table user
( userId int auto_increment primary key,
fullName varchar(100) not null
-- other columns
);
create table phoneType
( phoneType int auto_increment primary key, -- here is the code
long_description varchar(100) not null
-- other columns
);
create table userPhone
( id int auto_increment primary key,
userId int not null,
phone varchar(20) not null,
phoneType int not null,
-- other columns
CONSTRAINT fk_up_2_user FOREIGN KEY (userId) REFERENCES user(userId),
CONSTRAINT fk_up_2_phoneType FOREIGN KEY (phoneType) REFERENCES phoneType(phoneType)
);
Note1:
I suspect that your second table as you call it is really a third table, as you try to bring in missing information that really belongs in the Entity.
Entities
Many have come before you crafting our ideas as we slug it out in design. Many bad choices have been made and by yours truly. A good read is third normal form (3NF) for data normalization techniques.
Note2:
Performance. Performance needs to be measured both in real-time user and in developer problem solving of data that has run amok. Many developers spend significant time doing data patches for schemas that did not enforce data integrity. So factor that into performance, because those hours add up in those split seconds of User Experience (UX).
You can try this:-
INSERT INTO userDetails
(SELECT UserID, Name FROM User WHERE USerID= 102), 'Mob_No', EMail;