How to JOIN 4 table - php

Currently I have 4 tables. activity, category, pic and useraccount.
In this system, there's 2 user: applicant and person-in-charge. applicant will login and request for activity (which will be stored in table activity).
then depend on the category, person-in-charge will be assigned(will be stored in table pic with their name and activityID)
activity: `activityID`(PK), `username`, `categoryID`
category: `categoryID`(PK), `categoryName`
pic: `activityID`, `personincharge` (name of the pic)
useraccount: `name`, `username`
note: personincharge in table pic and name in table useraccount has the same value.
note 2: I will join table category and activity using categoryID to display the categoryname.
My system is going to have user log in by using username. I want to display table of activity record of the person in charge, which means it will only shows activity that the user(the one who logged in) is in charge of.
Currently I am only able to join table category and activity and display it. Here's what I have:
$sql = "
SELECT *
FROM activity a
JOIN category c
ON a.categoryID = c.categoryID
WHERE a.username= '".$_SESSION['username']."'";
Gone through so many trial and error but still cant find the answer. Thanks for the help in advance.
the flow of my system:
situation 1:
user login -> user request activity -> admin will pick the person in charge of the activity (the name of the pic will be insert into pic table along with the activityID)
situation 2:
pic login -> pic see the list of activity that he/she has been assigned to be in charge of and take action on the request.
**the situation 2 is what i'm currently stuck on. to display only activity he/she is assigned to.

If you are doing inner joins, then you can also join using the where clause, like so:
SELECT *
FROM activity as a,
category as c,
pic as p,
useraccount as u
WHERE a.categoryID = c.categoryID,
a.activityID = p.activityID,
p.personincharge = u.name

One:
Do not name your tables after smart shortcuts. Think what you are optimizing, and what you are loosing! Use "table AS t" shortcuts in actual queries.
Two:
Your table personsincharge contain the people responsible. Do a join with it. accountname is requester account. Once you join presonsincharge you have access to handlers
Three:
DO NOT USE POST VALUES TO CONCATENATE SQL STRINGS

You could have multiple joins in the same query like this:
$sql = "SELECT * FROM activity a
INNER JOIN category c ON a.categoryID=c.categoryID
INNER JOIN table_name as table_alias ON table_alias.ID = another_alias.ID
INNER JOIN ...
INNER JOIN ........
INNER JOIN ......
WHERE a.username= '".$_SESSION['username']."'";

Try this
select a.activityID, b.categoryName, c.personincharge, d.name
FROM activity a
LEFT JOIN category b ON b.categoryID = a.categoryID
LEFT JOIN pic c ON c.activityID = a.activityID
LEFT JOIN useraccount d ON d.username = a.username
WHERE d.username= '".$_SESSION['username']."'";

Related

How to SELECT SQL data using the results from a previous SELECT

Lets guess I have 3 tables:
Table a where I have a name and email
Table b where I have a text and user (as a reference to email from table a)
Table c where I have follower and following (both references to email in table a)
Im trying to develop a simple html/php/sql web that allows me to register many users and let them post different texts while also having the chance to follow or be followed by other users (already done) and I want to give an user the possibility to display the texts from table b that he himself posted and those from the users he is following
Im seriously struggling with how to extract this information
SELECT b.text
FROM tableB as b
LEFT JOIN tableC as c
ON b.user = c.follower
WHERE b.user = "currentuser"
This is as far as I got, which only shows the texts posted by the user himself (something I can do way more simple) but I cant seem to understand how to get those from the users he is following
I hope its understandable without any photo
You first want to find all following users in table c rows where the current user is the follower. Then you want to add the current user (or alternatively always have all users follow themselves). Then you want to find all texts for those users.
So:
select b.text
from (
select following as user
from tableC
where follower="current user"
union
select "current user"
) show_users
join tableB as b on b.user=show_users.user
or if you have a tableC row where follower=following for all users, just:
select b.text
from tableC as c
join tableB as b on b.user=c.following
where c.follower="current user"

PHP mySQL retrieve unique correct data from multiple tables

So i am making this webpage (for fun to practice web dev) where users can rate or comment on a movie. One page I have is where you click on the movie for full details and it lists all the ratings and comments (together if the user has commented by review and rated through a page called "reviewMovie"...which if they went this way the rating is mandatory, otherwise they can comment on this page "listMovieReviews").
The problem I am having is incorrect details when doing my queries
the discussion table stores: the discussion ID (primary key) the timestamp of the
comment, the comment, the user who made the comment, and the movie they commented
about.
the discussion table stores: the discussion ID (primary key) the timestamp of the
comment, the comment, the user who made the comment, and the movie they commented
about.
the rating table stores: the rating ID (primary key), the movie being rated, the
user who did the rating, and the rating score (out of 10)
So some examples of the combined data are:
User1 (user1) has rated "American Psycho" a 4/10 and has made a comment "comment1" on
it
User2 (admin..for testing purposes) has rated "American Psycho" a 8/10 and has made a
comment "comment2" on it
So on the page that lists the details of "American Psycho" and the ratings/comments I should have this list of ratings and comments:
<TIMESTAMP FOR COMMENT1> User1 Rating 4/10 "comment1"
<TIMESTAMP FOR COMMENT2> admin Rating 8/10 "comment2"
Using the following queries:
SELECT *
FROM discussion
INNER JOIN users ON discussion.userID = users.userID
WHERE discussion.movieID = <American Psycho's Movie ID>;
AND
SELECT *
FROM ratings
INNER JOIN movies ON ratings.movieID = movies.movieID
WHERE ratings.movieID = <American Psycho's Movie ID>;
I get this:
<TIMESTAMP FOR COMMENT2> admin Rating 4/10 "comment2"
<TIMESTAMP FOR COMMENT2> admin Rating 8/10 "comment2"
I have tried several other INNER JOINS with joining the table that stores user information and table that stores movies information but I keep getting mixed data
Also tried DISTINCT and UNION but still to no avail
Where am I going wrong??
Also first post so sorry If I have not been too clear, bad formatting, or not shown enough work but I am really really stuck
I assume:
A movie could have from 0 to n comments.
A movie could have from 0 to n ratings.
A user could rate a movie only once or none.
A user could comment a movie from 0 to n times.
Your queries are fine, maybe your problem is in your php code.
You have to account that a user maybe comment a movie several time and never rated it.
In second query you should JOIN with user (instead of with movie, because you do not get movie information) to get the user name.
Maybe you should display the info in two table: one for ratings and other for comments.
(You have to replace quotation marks by movie ID)
SELECT u.userName, r.score
FROM ratings AS r
INNER JOIN users AS u ON r.userID = u.userID
WHERE r.movieID = ?;
SELECT u.userName, d.commentTime, d.comment
FROM discussion AS d
INNER JOIN users AS u ON d.userID = u.userID
WHERE d.movieID = ?;
You could group all comments per user in one row this way (but I think this is not what you are looking for):
SELECT u.userName, GROUP_CONCAT(CONCAT(d.commentTime, ': ', d.comment) SEPARATOR '; ') AS comments
FROM discussion AS d
INNER JOIN users AS u ON d.userID = u.userID
WHERE d.movieID = ?
GROUP BY u.userName
I think do not have sense to make one query in this case, but if you want get all data in one query you could try something like this:
You will have a comment per row, so for example if a user make two comment you will have two rows for the same user with the same score.
First I get all user that comment or rating the selected movie and make a CROSS JOIN between movie and these users. Then I make a LEFT JOIN with discussion ON movieID and userID and another LEFT JOIN with ratings ON movieID and userID.
You need to make LEFT JOIN instead of INNER JOIN because if a movie do not have ratings or comments your result will be empty.
In SELECT clause you should list only the columns that you need.
SELECT *
FROM movies m
CROSS JOIN (SELECT d.userID
FROM discussion d
WHERE d.movieID = ?
UNION
SELECT r.userID
FROM ratings r
WHERE r.movieID = ?) AS u
LEFT JOIN discussion AS d ON m.movieID = d.movieID AND u.userID = d.userID
LEFT JOIN ratings AS r ON m.movieID = r.movieID AND u.userID = r.userID
LEFT JOIN users ON u.userID = users.userID
WHERE m.movieID = ?;
You need to join all three tables.
SELECT *
FROM movies AS m
JOIN ratings AS r ON r.movieID = m.movieID
JOIN discussion AS d ON d.userID = r.userID AND d.movieID = m.movieID
WHERE m.movieID = <American Psycho's Movie ID>
ORDER BY r.userID, d.timestamp
This will repeat the movie and rating information for each comment. You can remove those duplicates in the application code that displays the results. See How can i list has same id data with while loop in PHP? for an example of how to do this.
SELECT * FROM movies AS MOVIE
JOIN ratings AS RATING ON `RATING.movieID` = `MOVIE.movieID`
JOIN discussion AS DISCUS ON `DISCUS.userID` = `RATING.userID`
WHERE `MOVIE.movieID` = <SOME Movie ID>
ORDER BY `RATING.userID`, `DISCUS.timestamp`

how to make the link between my 2 sql tables?

I cannot correctly make the link between my 2 tables, I have a table that represents my users and another with appointments but I would like to make the link between the 2 to be able to display the appointments users.
My reservation table looks like this :
[tablebooking]
My user table looks like this :
[tableusers]
What I Tried :
[test]
If your appointment functionality is one to one relation like one appointment will have only one member then you can use below query(query followed fields from your screenshots)
SELECT
M.*, B.*
FROM
members AS M
INNER JOIN bookings AS B ON B.userid = M.userid
OR
if you want to have more than one members in one appointment, you need to have tables as below
[YOUR_USERS_TABLE_NAME] => Users list
[YOUR_BOOKINGS_TABLE_NAME] => List of appointments created
[YOUR_BOOKING_MEMBERS_TABLE_NAME] => It should have list of appointment id and members id(one(appointment) to many(users) relation)
and query will be like below
SELECT
B.*, U.*
FROM
[YOUR_BOOKINGS_TABLE_NAME] AS B
INNER JOIN [YOUR_BOOKING_MEMBERS_TABLE_NAME] AS M ON M.bookingid = B.id
INNER JOIN [YOUR_USERS_TABLE_NAME] AS U on M.userid = U.id
GROUP BY B.id, U.id
Hope my answer will help you.
Please add user_id in your bookings table and then run below query in your phpmyadmin.
select * from bookings as b INNER JOIN users as u ON u.id = b.user_id
Thanks.
You probably must use an external table to connect this tables.
EX:
foo{
id: primary,
idTableUser: external key,
idTableBooking: external key
}

mysql joins exlude matching records in another table

I am developing a networking site where I have to show random users profiles (excluding members who are already connected) to logged-in user to connect with. I have one members table which contains fields as memberid,firstname and lastname. I have another table for connections which has fields as memberid and friendid.
Now when I use left join on connections table, I get profiles of only connected members which I dont want. I only want to show profiles form members table which are not connected with logged-in user
You can achieve this without Join with the use of Not in.
select *from
members
where
members.memberid not in (select memberid
from connections
)
;
The above query simply means to display info of memberids that are not in connections.
EDIT:
Since you've already used Left join. here is the query to achieve this task with Left join:
select m.*
from members m
left join connections c
on m.id = c.id
where c.id is null;
Hope it helps!

Inner, outer or full join on three tables in MySQL database on linux with apache

I want to have some help creating my query to get information from three different tables sharing information in common.
My first table is:
auctions
id title description user_id(who posted it)
My second table is:
bids
id user_id bid auction_id owner_id
My third table is:
users
id username X XX XXX XXXX
...and my SQL is as follows however it's not returning any results:
SELECT auction_bids.user_id AS applicant, auction_bids.*, auctions.title FROM auction_bids, auctions
WHERE auctions.user_id=".$_SESSION['userid']."
INNER JOIN users ON auction_bids.user_id = users.id
WHERE auction_bids.owner_id = ".$_SESSION['userid']."
What I need is to capture the auction's title, username who bidded on the auction and the bid. the auction has to have a bid and posted by the user who owns the $_SESSION['userid'].
Any help is appreciated.
You have two different 'where' statements, which may just need combining;
SELECT auction_bids.user_id AS applicant, auction_bids.*, auctions.title FROM auction_bids, auctions
INNER JOIN users ON auction_bids.user_id = users.id
WHERE auction_bids.owner_id = ".$_SESSION['userid']." AND auctions.user_id=".$_SESSION['userid']."
However, I'm not sure this is really what you want, as it will return only records where the specific user both 'owns' the item AND has bidded on it (both based on the userid session), rather than displaying all records from different people who have bidded on an item 'owned' by the user.
Something like: ?
SELECT auction_bids.user_id AS applicant, auction_bids.*, auctions.title FROM auction_bids, auctions
INNER JOIN users ON auction_bids.user_id = users.id,
WHERE auction.owner_id = ".$_SESSION['userid']."
Hope this points you in the right direction!
you have 2 where clauses, that is incorrect. I have revised your query based on your requirements.
SELECT auction_bids.user_id AS applicant, auction_bids.*, auctions.title
FROM auction_bids, auctions
INNER JOIN users ON auction_bids.owner_id = users.id
WHERE auction_bids.owner_id = ".$_SESSION['userid']."
AND auctions.user_id=auctions_bids.owner_id

Categories