Using multiple columns in a join on same field in second table - mysql

Consider the following :
**Table 1 - record**
id (int primary key),
addedby (int),
editedby (int)
**Table 2 - users**
id (int primary),
name (shorttext)
**Sample Records**
record
0 1 1
1 1 2
users
1 user1
2 user2
What I need is so do a join to to be able to show the following :
record.id, users.addedby, users.editedby
I tried, amongst others, the following :
select record.id, users.name, users.name from record left join users on record.addedby=users.id left join users on record.editedby=users.id
However, it's not even logical that that will work, so I am a bit stuck.
Any help would be much appreciated. Thank you.

Just join the same table twice. Nothing unusual. You just have to alias the tables to be able to refer to them independently.
select r.id, u1.name added, u2.name editor
from record r
inner join user u1
on r.addedby = u1.id
inner join user u2
on r.editedby = u2.id
heres a demo

Use aliasses:
select record.id, users1.name, users2.name
from record
left join users users1 on record.addedby=users1.id
left join users users2 on record.editedby=users2.id

Related

Multiple joins off same table

I'm trying to connect two different types of users from the same users data table.
I have a database table with the following schema
agent_relationships
buyer_id
agent_id
I have a table with user data:
users
id
first name
last name
What i want is a data set that has the following:
buyer id first name
buyer id last name
agent id first name
agent id last name
I know im doing this incorrectly, but heres what I've attempted:
This one returns the same data for both buyer and agent, which i expected
select u1.first_name as buyerfirst,u1.last_name as buyerlast,u1.first_name as agentfirst,u1.last_name as agentlast from users u1 left join agent_relationships ar1 on ar1.buyer_id=u1.id left join agent_relationships ar2 on ar2.agent_id=u1.id
This one fails
select u1.first_name as buyerfirst,u1.last_name as buyerlast,u2.first_name as agentfirst,u2.last_name as agentlast from users u1,users u2 left join agent_relationships ar1 on ar1.buyer_id=u1.id left join agent_relationships ar2 on ar2.agent_id=u2.id
select BU.first_name, BU.last_name, AU.first_name, AU.last_name
from agent_relationships
left join users BU on buyer_id = BU.id
left join users AU on agent_id= AU.id
You need two join on user .. depending from agent_relationships
select u1.first_name as buyerfirst
,u1.last_name as buyerlast
,u2.first_name as agentfirst
,u2.last_name as agentlast
from agent_relationships ar
left join users u1 ar.buyer_id=u1.id
left join users u2 ar.agent_id=u1.id

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.

Duplicate values with multiple joins in query

I am trying to obtain comments made on a specific profile, but as soon as more than one person with a different relation (relation_id) to the profile has commented, I get duplicate, triplicate and so forth results.
Tables involved are as follows:
Users -
user_id
user_first_name
user_last_name
user_image path
Profile comments -
comment_id
profile_id
user_id
comment_body
comment_date
Profile_user_relation -
user_id
profile_id
relation_id
Relation_types -
relation_id
relation_name
My query is as follows:
SELECT profile_comments.*,
relation_types.relation_name,
users.user_first_name,
users.user_image_path
FROM profile_comments
LEFT JOIN profile_user_relation ON profile_comments.profile_id = profile_user_relation.profile_id
LEFT JOIN relation_types ON relation_types.relation_id = profile_user_relation.relation_id
LEFT JOIN users ON profile_comments.user_id = users.user_id
WHERE profile_comments.profile_id = :profileId
Thank you!
Didn't test it out, but I think it should work, or at least to get you a little bit closer.
SELECT
C.*,
RT.relation_name,
U.user_first_name,
U.user_image_path
FROM profile_comments AS C
JOIN users AS U USING(user_id)
JOIN profile_user_relation AS UR USING(user_id, profile_id)
JOIN relation_types AS RT USING(relation_id)
WHERE C.profile_id = :profileId
Hope that will be a bit helpful.

How to get data from database with condition on another table where something exist or not

I have a table for users like this
id | name | password | email
1 saeid ***** asd#asd.com
I have another table called appointments
id | created_by | due_date | notification_send
1 1 ***** 0
I want to get all users from users table where they have at least created one appointment in the appointments table (denoted by created_by field in the appointments table).
I have tried the code below but it fails:
SELECT * FROM users LEFT JOIN appointments a ON persons.id = a.created_by
But obviously it does not work.
One way is to use the exists predicate:
SELECT * FROM users u
WHERE EXISTS (SELECT 1 FROM appointments a WHERE a.created_by = u.id)
Alternatively you could use an inner join, but the exists query corresponds better to your question in my opinion (that is if you only need data from the users table).
The left join says to get all rows from users regardless if they have matching rows in appointments which is not what you want.
You are searching for a match between the table and so I would suggest doing a INNER JOIN rather like below
SELECT * FROM users u
JOIN appointments a ON u.id = a.created_by
Also check your ON clause once I think either this is a typo or a big mistake. You are selecting from users table then why persons.id??
ON persons.id = a.created_by
Try something like this:
http://sqlfiddle.com/#!9/5eba3/2
select * from users c where (select count(*) from appointments where created_by = c.id) > 0;

Using select statement with two tables

I have two tables. One contains User and company relationship a show below
User_company
UserId CompanyId
1 2
2 1
3 1
4 2
Another table holds user information
User
Id Name City
1 Peter LA
2 Harry SF
3 John NY
4 Joe CI
How do I make a statement which will give me All the users which are in company 1? Will something like
Select * from User where Id in (Select UserId from User_company where CompanyId = 1)
work?
SELECT * from User
left join User_company on User_company.UserId=User.Id
This would work...
SELECT * works but can be sluggish over time as it may not scale well with more data.
FROM User
WHERE Id in (Select UserId from User_company where CompanyId = 1)
So would this.. - best if you need data from both tables.
SELECT *
FROM User U
INNER JOIN User_Company UC
ON U.ID = UC.UserID
WHERE UC.CompanyID = 1
As would this - Probably the fastest if you just need data from user table.
Select * from User U
where exists (Select * from User_Company UC where U.ID = UC.UserID and CompanyID = 1)
OUTER joins are only needed if you need all records from one table and only those that match in another.
As to which is the best above: it depends on existing indexes and other requirements. Any of the above will return what's been asked for.
Try this
Select u.*
from User u
inner join User_company uc
on u.Id = uc.UserId
and uc.CompanyId = 1
BTW, what's wrong with the query you have posted? It will work as well fine. Just that it's a subquery and you better replace it with Join for performance.
Select * from User where Id in
(Select UserId from User_company where CompanyId = 1)
SELECT U.* FROM User AS U LEFT JOIN
User_company AS UC ON U.Id = UC.UserId WHERE UC.CompanyId = 1