Get results from multiple tables based on relationship table - sql

I have dbo.Users tables
Id, Name
1, John
2, Mary
3, Michael
Then I have dbo.Phones table
Id, Phonenumber
10, 1234
11, 5555
Then I have dbo.Relationship table
Id, ChildId
1, 10
2, 11
How could I make a query that returns
Id, Name, Phonenumber
1, John, 1234
2, Mary, 5555
3, Michael, NULL
This is what I got so far.
SELECT u.Id, u.Name, p.Phonenumber
FROM dbo.Users as u
LEFT JOIN dbo.Phones as p
-- Something
SQL Fiddle

Think of the Relationship table as the middle-man between your Users and Phones tables here. It is a many-to-many relationship with a mapping table. Join your Users to the Relationship and then the Relationship to your Phones.
SELECT u.Id
,u.Name
,p.PhoneNumber
FROM dbo.Users u
LEFT JOIN dbo.Relationship r ON r.Id = u.Id
LEFT JOIN dbo.Phones p ON p.Id = r.ChildId
Think of it like:
Users: Hello Relationship, I have UserId = 1, what PhoneIds do I have for that UserId?
Relationship: Hi Users. I have PhoneId = 10 for you. I'll go talk to Phones to see what the number is.
Phones: Hi Relationships! I have PhoneNumber 1234 for you. It matches the PhoneId you gave me.

Join them on id field.I would use inner join depending on the requirement
SELECT distinct u.Id, u.Name, p.Phonenumber
FROM dbo.Users as u
LEFT JOIN dbo.Phones as p on u.id = p.id
or---
SELECT distinct u.Id, u.Name, p.Phonenumber
FROM dbo.Users as u
inner join T JOIN dbo.Phones as p on u.id = p.id
inner join dbo.relationship r on r.id = u.id
where----

try this :
Select u.Id, u.Name, p.Phonenumber
From
Users u
Left join Relationship r on r.Id = u.Id
Left join Phones p on r.ChildId = p.Phonenumber

Related

SQL SUM and COUNT from different tables

Tables:
UserReward:
UserRewardID PK
RewardID FK
UserID FK
UserBadge:
UserBadgeID PK
BadgeID FK
UserID FK
UserScore:
UserScoreID PK
UserID FK
LeaderboardID FK
I need to know the sum of score, the count of userbadge and the count of userReward.
I tried this but values are not right:
Select
u.username,
sum(us.score) as Soma_Score,
count(ur.userId) as Numero_de_rewards,
count(ub.userId) as Numero_de_crachas
from [user] u
join userscore us on u.userId = us.userID
join userbadge ub on ub.userid = u.userid
join userreward ur on ur.userid= u.userid
group by u.username
Have you looked at the rows before aggregating them? Your JOINs are duplicating many rows.
The best approach is to join the rows after aggregation:
with score(userid, score) as (
Select userid
, sum(us.score) as Soma_Score
from userscore us
group by userid
), rewards (userid, rewards) as (
select userid
, count(ur.userId) as Numero_de_rewards
from userreward ur
group by userid
), crachas (userid, crachas) as
select userid
, count(userId)
from userbadge
group by userid
)
select
u.userid
, score.score
, rewards.rewards
, crachas.crachas
from user u
left join score on u.userid=score.userid
left join rewards on u.userid=rewards.userid
left join crachas on u.userid=crachas.userid
Try:
SELECT
u.username,
(SELECT SUM(us.score) FROM userscore us WHERE us.userid = u.userid) as Soma_Score,
(SELECT COUNT(ur.userId) FROM userreward ur WHERE ur.userid = u.userid) as numero_de_rewards,
(SELECT COUNT(ub.userId) FROM userbadge ub WHERE ub.userid = u.userid) as numero_de_crachas
FROM [user] u

How to combine two SQL queries in one

I have tables user, participant and chat. I need to get all users in a specific chat and amount of chats that user in by chat name. For example current tables:
user chat participant
id|name id|name user_id|chat_id
1|Mike 1|School 1|1
2|John 2|Football 2|1
3|Sara 3|Gym 1|2
3|3
And by keyword "School" I want to get this
Mike|2
John|1
I have two queries to get first and second column in result but don't know how to combine it:
SELECT user.name FROM user
JOIN participant ON (user.id = participant.user_id)
JOIN chat ON (participant.chat_id = chat.id) WHERE chat.name = 'School';
That gives me
Mike
John
And
SELECT user.name, COUNT(*) FROM user
JOIN participant ON (user.id = participant.user_id) GROUP BY user.name;
returns
John|1
Mike|2
Sara|1
So how to combine it?
TRY THIS
SELECT p1.name, COUNT(p.user_id) totUser
FROM participant p
INNER JOIN (select u.id, u.name FROM participant p
inner JOIN chat c ON c.id = p.[chat_id]
INNER JOIN user u ON u.id = p.user_id
AND c.name = 'School') p1 ON p1.id = p.user_id
GROUP BY p1.name
using Subquery and joins :
select u.name,count(p.chat_id) as 'Count' from user u
inner join participant p on p.user_id = u.id
where
p.user_id in ( select user_id from participant pp inner join chat cc on cc.id = pp.chat_id where
cc.name = 'School' )
group by u.name
order by Count desc
Output :

Inner Join of 3 Tables

In Table Approver:
No Userid
1 3
2 7
In Table Users:
No UserID RoleID
1 3 1
2 4 1
3 5 2
4 7 3
Table Roles
RoleID Name
1 ABC
2 BCD
3 CDE
I want to select rolename of users in table approver like:
Userid Name
3 ABC
7 CDE
I'm not 100% sure why approver.no is on the user and approver table.... I'm going to assume userId is unique in both situation..... if thats the case this should work:
select
u.userid,
r.name
from
Approver as a
inner join [Users] as u on a.userId = u.UserId
inner join [Roles] as r on u.roleId = r.roleId
if that is NOT the case and you need the approver.no user.UserId combo to be unique than the following should work:
select
u.userid,
r.name
from
Approver as a
inner join [Users] as u on a.userId = u.UserId
and a.No = u.No
inner join [Roles] as r on u.roleId = r.roleId
the differences between these two as far as the result set concerns can be found here: http://sqlfiddle.com/#!3/0daa9/4
Notice that the second query returns a single result against the provided data
select
a.Userid,
r.Name
from
Approver a
join Users u on a.no = u.no
join Roles r on u.RoleID = r.RoleID
SELECT U.UserID,
Name
FROM Approver A
JOIN Users U
ON A.UserId = U.UserId
JOIN Roles R
ON R.RoleId = U.RoleId
SQL FIDDLE DEMO
SELECT Approver.UserId, Name from Approver INNER JOIN Users
on Approver.No=Users.No
INNER JOIN Roles
on Users.RoleID=Roles.RoleID

retrieving values from 3 one-to-one relationship table (Oracle)

Each Student and Teacher have their own UNIQUE UserID
Is it possible to retrieve the values from the three tables at once?
such that: it will display the UserID owned by each Student or Teacher?
I've tried the following query, but it doesn't work:
SELECT u.UserID, StudentID, TeacherID
FROM User u
INNER JOIN (SELECT * FROM Student, Teacher) ss
ON u.UserID = ss.UserID
Maybe this way:
SELECT u.UserID, S.StudentID, T.TeacherID
from User U
left join Student S on S.UserID = u.UserID
left join Teacher T on T.UserID = U.UserID

sql optimize search many-many

usertable
----
id, username
grouptable
----
id, groupname
group_user
--------
uid, gid
books
----
id, groupname
Input parameters: groupname, username
output: list of books
Is it possible to use 1 sql statement to get list of books when username is inside groupname
Question 2: any good book to recommand to master complex sql statement..
This query gives list of books by user parametar
SELECT b.id,
FROM usertable u
INNER JOIN group_user gu ON gu.uid = u.id
INNER JOIN grouptable g ON g.id= gu.gid
INNER JOIN books b ON b.groupname = g.groupname
WHERE u.username = #user_name
Also i think if you have the group name you can use
SELECT b.id,
FROM grouptable g
INNER JOIN books b ON b.groupname = g.groupname
WHERE g.groupname = #group_name
Bus having select on both parameters i think is not very good think. This query will get
list of books for user group name
SELECT b.id,
FROM usertable u
INNER JOIN group_user gu ON gu.uid = u.id
INNER JOIN grouptable g ON g.id= gu.gid
AND g.group_name = #group_name
INNER JOIN books b ON b.groupname = g.groupname
WHERE u.username = #user_name