Is it really necessary to create foreign key in this query? - mysql

I have a table called investors having a primary key as ID. I also have additional tables named Users Login_Logs and Accounts. All of these tables contain the foreign key investor_id. Between investors and Users we have a one to one relation. between investors and Login_Logs a one to many relation and between investors and Acccounts a one to many relation as well. My question is in order to create a query that loads info contained in the table Users, Login_Logs and Accounts - do I need to store the Users id, Accounts id and Login_Logs id in the investors table? I mean, do I need to create foreign keys in the investors table for all columns?

No, foreign key constraints don't affect joins and read queries. They ensure that the values in the child column(s) exist in the referenced column(s). They're used for integrity, not for linking rows or tables.
AFAICT recording the user id in your investors table is redundant, and recording the account and login_log ids in investors isn't practical.
To be able to join the tables efficiently, what you need is to index the investor_id in each of the tables. Then, it's up to your query to connect the tables as required.
The problem with retrieving all the information about investors at the same time is that you have (multiple) one-to-many relations. If we join all the tables:
SELECT *
FROM investors i
JOIN users u ON i.ID = u.investor_id
JOIN accounts a ON i.ID = a.investor_id
JOIN login_logs l ON i.ID = l.investor_id
Then, if an investor has 2 accounts and 2 login_logs, then we'll get 4 rows. SQL databases can't nest related data. Instead, you may have to use 3 queries to retrieve everything about investors:
SELECT *
FROM investors i
JOIN users u ON i.ID = u.investor_id
SELECT *
FROM accounts
SELECT *
FROM login_logs
Then process the results in code. You could process the combined query above programmatically, but it's a bit more complicated.

Related

how to Join only part of my first table to another table?

i have three tables:
account (which contain accounts Registered info and that Primary key is ads_id)
ads_info (which contain my advertising info and that Primary Key is ads_id)
favorite_ads (which that columns is fav_id, acc_id And ads_id) that specifies witch User Favorite which advertising.
Now i want to separate records which have acc_id = 1 from favorite_ads table and then outer-join this records with all of my ads_info table records.
can tell my any sql query do some thins like it for me?
You may try below query -
SELECT *
FROM ads_info AI
LEFT JOIN (SELECT fav_id, acc_id, ads_id
FROM favorite_ads
WHERE acc_id = 1) FA ON AI.ads_id = FA.ads_id

What type of Data Relationships would I use for setting up 3 tables and connect to them

I'm trying to run a query that would SELECT * FROM teachers WHERE users.school = teachers.school AND WHERE users.grade = teachers.grade.
I'm setting up three tables, users, teachers and schools. The users are the parents and admins at the school, they sign up with an access_code that matches up in the school table. Same for the teachers, but their info is stored in the teacher's table. (Each user and teacher are associated with a school and grade both are in their tables). I want to show the user all the teachers info at the users' school.
I have all the info for the schools table id, school, and access_codes, but how would I go about achieving this? Would I use a JOIN or FOREIGN KEY?
I've tried some JOIN's, but I'm not that familiar with them. I looked at the FOREIGN KEY but not sure how to use it. Any help would be very much appreciated .
foreign key if for constarints
for build the relation you can use join eg:
SELECT *
FROM teachers
INNER JOIN users ON users.school = teachers.school
AND users.grade = teachers.grade
Anyway in you pseudo code you have only two table teachers and users
I kind a found a work around to my problem
SELECT * FROM teachers WHERE school =
(
SELECT school FROM users WHERE id = ".$id = $_SESSION['id']."
)
GROUP BY grade
This is a start it's not perfect but if I add another session for grade I think it will work.

How to join three tables that linked to one table in MySQL?

How do I join three tables that are all linked to one table?
For example, I need to join a term table, a student table and a course table in a University db.
All these tables are linked to just the section table and none other table, but I need to retrieve data from all three tables.
You will have a key relationship between these tables.
ex: you will have a courseid in Course table and the same as a foreign key reference in Student table.
You should decide on what type of join(INNER, OUTER) you need.
From your requirement:
You need sum of the number of credits selected for each term by students. For this you can use the below query.
select selection.student_id, selection.course_id, selection.term_id, sum(course.credits) from selection
join student on selection.student_id = student.id
join course on selection.course_id = course.id
join term on selection.term_id = term.id
group by selection.student_id, selection.course_id, selection.term_id

Get stats table from a many to many relationship

I have a pivot table for a Many to Many relationship between users and collected_guitars. As you can see a "collected_guitar" is an item that references some data in foreign tables (guitar_models, finish).
My users also have some foreign data in foreign tables (hand_types and genders)
I want to get a derived table that lists data if I look for a particular model_id in "collected_guitar_user"
Let's say "Fender Stratocaster" is model id = 200, where the make is Fender (id = 1 of makes table).
The same guitar could come in a variety of finish hence the use of another table collected_guitars.
One user could have this item in his collection
Now what I want to find by looking at model_id (in this case 200) in the pivot table "collected_guitar_user" is the number of Fender Stratocasters that are collected by users that share the same genders.sex and hand_types.type as the logged in user and to see what finish they divide in (some percent of finish A and B etc...).
So a user could see that is interested in what others are buying could see some statistics for the model.
What query can derive this kind of table??
You can do aggregate counts by using the GROUP BY syntax, and CROSS JOIN to compute a percentage of the total:
SELECT make.make, models.model_name as model, finish.finish,
COUNT(1) AS number_of_users,
(COUNT(1) / u.total * 100) AS percent_owned
FROM owned_guitar, owned_guitar_users, users, models, make, finish
CROSS JOIN (SELECT COUNT(1) AS total FROM users) u
WHERE users.id = owned_guitar_users.user_id
AND owned_guitar_user.owned_guitar_id = owned_guitar.id
AND owned_guitar.model_id = models.id
AND owned_guitar.make_id = make.id
AND owned_guitar.finish_id = finish.id
GROUP BY owned_guitar.id
Please note though, that in cases where a user owns more than one guitar, the percentages will no longer necessarily sum to unity (for example, Jack and John could both own all five guitars, so each of them owns "100%" of the guitars).
I'm also a little confused by your database design. Why do you have a finish_id and make_id associated directly in the owned_guitar table as well as in the models table?

MySQL multiple tables relationship (code opinion)

I have 4 tables: rooms(id, name, description), clients(id, name, email), cards(id, card_number, exp_date, client_id) and orders(id, client_id, room_id, card_id, start_date, end_date).
The tables are all InnoDB and are pretty much simple. What I need is to add relationships between them. What I did was to assign cards.client_id as a Foreign Key to db.clients and orders.client_id, orders.room_id and orders.card_id as Foreign Keys to the other tables.
My question: is this way correct and reliable? I never had the need to use Foreign Key before now and this is my first try. All the Foreign Keys are also indexes.
Also, what's the easiest way to retrieve all the information I need for db.orders ?
I need a query to output: who is the client, what's his card details, what room/s did he ordered and what's the period he's checked in.
Can I accomplish this query based on the structure I created?
You must create the FK's in all columns that relate to other tables. In your case, create on: cards.client_id, orders.client_id, orders.room_id, orders.card_id
In the case of MySQL it automatically creates indexes for these FK's.
On your select, I believe it can be the following:
SELECT * FROM orders
INNER JOIN client on client.id = orders.client_id
INNER JOIN cards on cards.client_id = client.id
INNER JOIN rooms on rooms.id = orders.room_id
I do not know what columns you need, there is only you replace the * by the columns you need, so SQL is faster.