Join on two of the same foreign keys - sql

I have this table below
Table Assignments
AssignmentID: int
LinkedTo: varchar(50)
AssignedUser: int
AssignedBy: int
where AssignedBy and AssignedUser are foreign keys from the table Users. Here is what Users looks like
UserKey:int
Username:varchar(50)
How can I do an inner join where I get both AssignedBy and AssignedUser?
The following gives me one of them but how can I get both? By the way AssignedBy and AssignedUser are two different Users. I'm trying to get Users.Username
select Users.Username
from Assignments
INNER JOIN Users ON Assignments.UserKey = Users.UserKey

If you want both user names on one row, you have to join Users twice, like
SELECT UA.Username AS AssignedUserName, UB.Username AS AssignedByUserName
FROM Assignments A
INNER JOIN Users UA ON A.AssignedUser = UA.UserKey
INNER JOIN Users UB ON A.AssignedBy = UB.UserKey;
If your goal is to have all user names regardless wether it comes from AssignedUser or from AssignedBy, you have to use UNION
SELECT U.Username
FROM Assignments A
INNER JOIN Users U ON A.AssignedUser = U.UserKey
UNION SELECT U.Username
FROM Assignments A
INNER JOIN Users U ON A.AssignedBy = U.UserKey;
Note however that this will remove duplicate user names. If you want to keep duplicates, use UNION ALL.

You need two joins:
SELECT assigned.username AS assigned_username
assigned_by.username AS assigned_by_username
FROM assignments a
JOIN users assigned ON a.assigneduser = assigned.userkey
JOIN users assigned_by ON a.assignedby = assigned_by.userkey

Related

How to join tables having many to many relationship

I am trying to JOIN four tables together, one table is a joining table as two of the tables have many-to-many relationship:
What would be the query to select DispalyName from User, Name & Description from Role and Permission & Description from Permission.
I know how to join two tables together, but my method of doing so does not work on this problem.
I have tried the following query but it doesn't seem to like it.
SELECT org.[User].[DisplayName], org.[Role].[Description], org.[Permission].[Description]
FROM org.[Role] rolee
JOIN org.[RolePermissions] rolePerms ON rolee.ID = rolePerms.RoleId
JOIN org.[Permission] perms ON rolePerms.PermissionId = perms.ID
WHERE [User].[email] LIKE '%myemail%'
Try this - It seems that You forget to join with the user table
SELECT org.[User].[DisplayName], org.[Role].[Description], org.[Permission].[Description]
FROM org.[User] user Join org.[Role] rolee on user.RoleID = rolee.ID
JOIN org.[RolePermissions] rolePerms ON rolee.ID = rolePerms.RoleId
JOIN org.[Permission] perms ON rolePerms.PermissionId = perms.ID
WHERE org.[User].[email] LIKE '%myemail%'
You need to join User
SELECT u.[DisplayName], r.[Description], p.[Description]
FROM org.[Role] r
JOIN org.[RolePermissions] rp ON r.ID = rp.RoleId
JOIN org.[Permission] p ON rp.PermissionId = p.ID
JOIN org.[User] u ON r.Id = u.RoleID
WHERE u.email LIKE '%myemail%'

SQL Where on different table

SELECT * FROM student_mentor sm INNER JOIN users u
ON sm.student_id = u.user_id
WHERE sm.teacher_id = $teacher_id
Teacher_id being the session id,
I want to see all the students that have the same mentor.
Right now if I run this I just see all of the students twice, maybe one of you knows why?
My db scheme
You are not specifying on which columns you want to do the join, so you're getting a cross reference where all records are joined to all records.
You should do something like (not sure about your column names):
SELECT * FROM student_mentor sm INNER JOIN users u
ON sm.student_id = u.user_id
WHERE sm.teacher_id = $teacher_id

Sql match id's with names from a table that matches with another table

I have a table friend which has two columns with Id's that belong to specific usernames. See example:
Id_Gebruiker is the user and Id_Gebruiker2 is the friend of the user.
The table friend has id's that belong to the table user.
Then that table user has Foreign Keys (column Id_Client) to the table client (referencing the Id_Client column). The client table contains the usernames.
Now I want to get the corresponding usernames that belongs to the Id's that the Friend table contains. So far I got it working when I use only two tables but I can't get it to work with three tables.
Something like this?
select f.Id_Gebruiker, f.Id_Gebruiker2, u.Id_Client, c.Gebruikersnaam
from friend f
join [user] u on f.Id_Gebruiker2 = u.Id
join client c on u.id_client = c.id
EDIT Assuming the names of the users are on the same table (client) and that every friend.Id_Gebruiker corresponds to a client.Id (so there exists a FK relationship), you can find both names with an extra join:
select c.Gebruikersnaam as UserName, c2.Gebruikersnaam as FriendName
from friend f
join client c on f.Id_Gebruiker = c.Id
join [user] u on f.Id_Gebruiker2 = u.Id
join client c2 on u.id_client = c2.id
Here is another answer that you can check and verify at http://sqlfiddle.com/#!3/2b9dd/1.
The main query for getting names for userid and friendid in friends table is as below.
SELECT f1.userid,
f1.friendid,
y.username AS UserName,
x.username AS FriendName
FROM friends f1
INNER JOIN (SELECT DISTINCT f.friendid,
c.clientname AS UserName
FROM users u
INNER JOIN clients c
ON u.id_client = c.id
INNER JOIN friends f
ON f.friendid = u.id) x
ON f1.friendid = x.friendid
INNER JOIN (SELECT DISTINCT f.userid,
c.clientname AS UserName
FROM users u
INNER JOIN clients c
ON u.id_client = c.id
INNER JOIN friends f
ON f.userid = u.id) y
ON f1.userid = y.userid;

Using binary logic in PostgreSQL JOIN queries

I've got 3 tables that look vaguely like this:
Users
----------
UserID
Name
Phone
User Groups
-----------
GroupID
Activity
Group Membership
---------------
UserID
GroupID
Independent Actives
-------------------
UserID
Activity
The idea is that a user can perform an activity either as part of a group or on their own. What I want to do is return all the people that partake in a certain activity. What I have been able to write so far lets me return all the users which are in groups that undertake that activity. What I want to add to this is the ability to see the people that do the activity independently. This is what I have so far:
SELECT
users.name, users.phone, user_groups.activity
FROM users
INNER JOIN group_membership ON group_membership.userID = users.userID
INNER JOIN user_groups ON user_groups.groupID = group_membership.groupID
WHERE user_groups.activity = 'Knitting';
The above bit works fine and it shows all of the users that are part of groups that do knitting, but I also want it to show all the users that are knitting independently. This is what I have attempted to add:
SELECT
users.name, users.phone, user_groups.activity
FROM users
INNER JOIN group_membership ON group_membership.userID = users.userID
INNER JOIN user_groups ON user_groups.groupID = group_membership.groupID
INNER JOIN independent_activity ON independent_activity.userID = users.userID
WHERE user_groups.activity = 'Knitting' OR independent_activity.activity = 'Knitting';
The problem here is the syntax, I understand the algorithm that I'm trying to do but I don't know how to transfer it into sql and so any help is appreciated.
You could use a UNION in this case
SELECT users.NAME
,users.phone
,user_groups.activity
FROM users
INNER JOIN group_membership ON group_membership.userID = users.userID
INNER JOIN user_groups ON user_groups.groupID = group_membership.groupID
WHERE user_groups.activity = 'Knitting'
UNION
SELECT users.NAME
,users.phone
,independent_activity.activity
FROM users
INNER JOIN independent_activity ON independent_activity.userID = users.userID
WHERE independent_activity.activity = 'Knitting';
You also might want to lookup the differences between a UNION and a UNION ALL and decide the one that suites your requirement.
You've got a working answer from SoulTrain. However, for completeness sake I'd like to mention that you don't have to join all those tables. (You could use outer joins here and remove duplicate matches with DISTINCT, but that's not necessary. You don't have to query the users table twice either. And you don't need UNION for doing the distinct job.)
Simply select from the one table you want to display data from, i.e. the users table, and then use EXISTS or IN to get only those users that are either in one set or another.
select name, phone
from users
where userid in
(
select userid
from independent_actives
where activity = 'Knitting'
)
or userid
(
select userid
from group_membership
where groupid in (select groupid from user_groups where activity = 'Knitting')
)

Selecting records in SQL based on another table's contents

I'm a bit new to SQL and have trouble constructing a select statement. I have two tables:
Table users
int id
varchar name
Table properties
int userID
int property
and I want all user records which have a certain property. Is there a way to get them in one SQL call or do I need to first get all userIDs from the properties table and then select each user individually?
Use a JOIN:
SELECT U.id, U.name, P.property FROM users U
INNER JOIN properties P ON P.userID = U.id
WHERE property = 3
If there's only one property row per user you want to select on, I think this is what you want:
select
users.*
from
users,
properties
where
users.id = properties.userID
and properties.property = (whatnot);
If you have multiple property rows matching "whatnot" and you only want one, depending your database system, you either want a left join or a distinct clause.
Check out the JOIN command. You could write a query like the following:
SELECT
name
FROM
users u
INNER JOIN properties p
ON u.id = p.userID
WHERE
p.property = <some value>
You're looking to JOIN tables.
Assuming the id and userID columns have the same meaning, it's like this:
select u.name
from users u inner join properties p
on u.id = p.userID
where p.property = :ValueToFind
SELECT [Name] FROM Users u
JOIN Properties p on p.UserID=u.ID
WHERE p.Property=1
Obviously it depends what flavour of RDBMS and TSQL you are using.