MYSQL Join Multiple times on same table - mysql

I am trying to pull both owner and editby. Both of those fields are INT. Inside a simple table, for example:
users:
user_id user_name
-----------------
2 johnny
3 mecca
doc:
owner content editby
----------------------
2 misc 3
SQL:
SELECT doc.owner, doc.content, doc.editby, users.user_name
FROM doc
LEFT JOIN
users
ON
users.user_id = doc.owner
WHERE
doc_id = $id
I can grab owner user_name, but I am not sure how to obtain editby on the same table. How do I go about pulling the different user names for different id fields multiple times?

Join the users table twice with different aliases
SELECT doc.owner, doc.content,
e.user_name as editor,
o.user_name as owner
FROM doc
LEFT JOIN users o ON o.user_id = doc.owner
LEFT JOIN users e ON e.user_id = doc.editby
WHERE doc_id = $id

Related

select user with more than one category

now here I have these tables, user can have more than category, and I want to show table like this
I've wrote this statement but It repeats user name with every category
SELECT
c.name
FROM
permission p
JOIN users u
ON u.id = p.user_id
JOIN category c
ON c.id = p.category_id
USER DATA TABLE // this table is what I want to get because every user have more than one category
username
email
categories
row
row
math, science
row
row
row, row, row
//those tables are what I have in the database
USERS TABLE
USER ID
username
email
5
row
row
6
row
row
CATEGORY TABLE
C ID
C NAME
8
math
9
science
PERMISSION TABLE
ID
USER ID
C ID
1
5
8
2
6
9
If you have only username use DISTINCT
SELECT DISTINCT
c.name
FROM
permission p
JOIN
users u ON u.id = p.user_id
JOIN
category c ON c.id = p.category_id
With more columns you should look for GROUP BY c.name
As user info in users table is unique so max keyword is used for optimization purpose. If same category is mapped multiple times with single user then use DISTINCT keyword inside GROUP_CONCAT functions. GROUP_CONCAT() is build in function for MySQL.
-- MySQL
SELECT MAX(u.username) username
, MAX(u.email) email
, GROUP_CONCAT(c.cname) categories
FROM users u
INNER JOIN permission p
ON u.userid = p.userid
INNER JOIN category c
ON c.cid = p.cid
GROUP BY u.UserID;

How to Join three tables properly

The main table has 4 columns:
User Activity Table
userActivityId userId therapistId activityId
1 1 1 1
Each of these columns is a table and these values are all foreign keys.
Basically im trying to run a query that will join to the users table and pull their first and last name based off the user Id.Same thing with therapist - join to the therapist table, pull first + last name.And finally Join to the Activity table and pull the activity name and path from the activity Id
The other tables look like this:
User Table
userId fName lName
Therapist Table
therapistId therapistFirstName therapistLastName
Activity Table
activityId activityTitle activityPath
So far my query looks like
SELECT
User_Activities.userId,
User_Activities.therapistId,
User_Activities.activityId,
Activities.activityTitle,
Activities.activityPath,
Users.fName,
users.lName,
Therapists.therapistFirstName,
Therapists.therapistLastName
FROM
User_Activities
INNER JOIN Users
ON User_Activities.userId = Users.userId
INNER JOIN Therapists ON
User_Activities.therapistId = Therapists.therapistId
INNER JOIN Activities ON
Activities.activityId = User_Activities.userActivityId
WHERE
User_Activities.userId = 1;
When I run this query It only returns 1 row as a result. However there are two activities in the User_Activites table assigned to userId 1.
If I change : INNER JOIN Activities ON
Activities.activityId = User_Activities.userActivityId
from an INNER JOIN to the LEFT JOIN it will display the second row, however the activityTitle and activityPath will be displayed as NULL in the second row.
userActivityId userId therapistId activityId activityId activityTitle activityPath fName lName therapistFirstName therapistLastName
1 1 1 1 1 Brain GZZ0zpUQ S C M D
11 1 1 1 NULL NULL NULL S C M D
You have pretty much answered your question. The second activity does not have a valid ActivityId.
If you want all activities for a user, then you should phrase the query as:
SELECT . . .
FROM Users u LEFT JOIN
User_Activities ua
ON ua.userId = u.userId LEFT JOIN
Therapists t
ON ua.therapistId = t.therapistId LEFT JOIN
Activities a
ON a.activityId = ua.userActivityId
WHERE u.userId = 1;
You want to start with the table where you want to keep all the rows. Then use LEFT JOIN to bring in other tables.
Two other changes of note:
Table aliases are used to simplify reading and writing the query. The SELECT needs to change to use the aliases.
The WHERE clause refers to the Users table rather than UserActivities.

Join two tables on a specific table fields

I have two tables activity_log and user_followers. I have to join these two tables and get the activity of a user with the user activity that he is following (let's say user_id 6 is following user_id 4). But the below query only returning the activity of the user having the id of 6. I want to get the activity of the user with the id of 6 plus the activity of the user he is following.
Query
SELECT activity_log.*
FROM activity_log
join user_followers ON activity_log.user_id = user_followers.follow_id
AND activity_log.user_id = 6;
activity_log:
user_followers:
Sounds like you want user_id 6's activity plus activity of users he's following. That would be:
SELECT activity_log.*
FROM activity_log
LEFT OUTER JOIN user_followers
ON activity_log.user_id = user_followers.follow_id
WHERE (activity_log.user_id = 6 OR ISNULL(user_followers.user_id,0) = 6);
The LEFT OUTER is used in case user_id 6 has no followers.

basic join on mysql

I am having a hard time understanding joins on mySQL, and I cannot find any similar example to work with.
Suppose I have two tables: users and users_info.
in users I have id, email and password fields while, in users_info I have all their information, like name, surname, street, etc.
so, if I am getting a user like this:
SELECT * FROM users WHERE id = 43
and their information like this:
SELECT * FROM users_info WHERE id = 43
I will basically get 2 results, and 2 tables.
I understand now that I need to use join so that they are all together, but I just can't figure out out.
Any help?
It seems like both tables users and user_info are related with each others by the column id therefore you need to join them using this column like this:
SELECT
u.id,
u.email,
u.password,
i.name,
i.surname,
i.street
FROM users AS u
INNER JOIN user_info AS i ON u.id = i.id;
This will only select the fields id, email, ... etc. However, if you want to select all the columns from both the tables use SELECT *:
SELECT *
FROM users AS u
INNER JOIN user_info AS i ON u.id = i.id;
If you want to input the id and get all of these data for a specific user, add a WHERE clause at the end of the query:
SELECT *
FROM users AS u
INNER JOIN user_info AS i ON u.id = i.id
WHERE u.id = 43;
For more information about JOIN kindly see the following:
Join (SQL)From Wikipedia.
Visual Representation of SQL Joins.
Another Visual Explanation of SQL Joins.
Here's an example
SELECT * FROM users u
INNER JOIN users_info i
ON u.id=i.id
this means, you are joining users table and users_info table
for example
users
id name
---- -------
1 abc
2 xyz
users_info
id email
--- ------
1 abc#aaa.com
2 xyz#aaa.com
the query will return
id name email
--- ----- -------
1 abc abc#aaa.com
2 xyz xyz#aaa.com
Here's a nice tutorial
You can also do:
SELECT users.*, users_info.*
FROM users, users_info
WHERE users.id = users_info.id AND users.id = 43;
This means:
"Get me all the columns from the users table, all the columns from the users_info table for the lines where the id column of users and the id column of users_info correspond to each other"

SQL Join and show results if join false

I have a table - comments. Users can post if not a member of the site but want to show their details if they are.
So if a user comments who is NOT a member I show their posts but don't link to their profile, because they don't have one.
So, in the following query I want to return the rows even if there is no join:
select wc.comment, wc.comment_by_name, wc.user_id, u.url from comments wc
join users u on wc.wag_uid = u.user_id
where id = '1237' group by wc.comment order by wc.dateadded desc
I want to return:
comment comment_by_name user_id url
------- --------------- ------- ----
hello dan 12 /dan
hey jane /jane
world jack 10 /jack
But the above does not return the data for jane as she does not have a user_id
Is there a way to return all data even if the join is null?
use LEFT JOIN instead
SELECT wc.comment, wc.comment_by_name, wc.user_id, u.url
FROM comments wc
LEFT JOIN users u
on wc.wag_uid = u.user_id
WHERE id = '1237'
GROUP BY wc.comment
ORDER BY wc.dateadded DESC
basically INNER JOIN only select records which a record from one table has atleast one match on the other table while LEFT JOIN select all rows from the left hand side table (in your case, it's comments) whether it has no match on the other table.