JOIN the table if records exist - sql

is it possible if i want to do INNER JOIN only if the record exist on the 2nd table if not then dont join?
this is my table
User table
+--------+--------------+
| id | name |
+--------+--------------+
| 1 | John |
+--------+--------------+
| 2 | Josh |
+--------+--------------+
House table
+--------+-------------+--------------+
| id | owner_id | house_no |
+--------+-------------+--------------+
| 1 | 1 | 991 |
+--------+-------------+--------------+
this is my INNER JOIN query
SELECT h.owner_id, u.name, h.house_no FROM user u
INNER JOIN house h on u.id = h.owner_id
WHERE u.id = :id
it will return this result if id = 1
+--------+--------------+--------------+
| id | name | house_no |
+--------+--------------+--------------+
| 1 | John | 991 |
+--------+--------------+--------------+
but if i run with id = 2 no result returned.
what i want to do right now is it still return the result even when no data exist for id = 2 in table house

Use a left outer join instead.
SELECT u.id, u.name, h.house_no FROM user u
LEFT OUTER JOIN house h on u.id = h.owner_id
WHERE u.id = :id
The resulting record will be:
+--------+--------------+--------------+
| id | name | house_no |
+--------+--------------+--------------+
| 2 | Josh | null |
+--------+--------------+--------------+

Related

How do I receive a pair of ids of entities in many-to-many relation with null value for the second id if condition is not met

I've got the following tables: person (id), person_agency (person_id, agency_id) and agency(id, type)
this is my query:
select p.id, a.id from person p
left join person_agency pa on p.id = pa.person_id
left join agency a on pa.agency_id = a.id
where a.type = 'agency_type1'
However, with the query I get only the persons who have a relation with an agency of "agency_type1". Instead, I would like to get a list of ids of ALL persons with ids of agencies, where the relation exists and null where it doesn't. I tried naive outer joins but it did not work.
For this content of the tables:
Person:
+-------+
| id |
+-------+
| 1 |
| 2 |
| 3 |
| 4 |
+-------+
Person_agency:
+-----------+-----------+
| person_id | agency_id |
+-----------+-----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 4 |
| 4 | 5 |
+-----------+-----------+
Agency:
+--------+------------------+
| id | type |
+--------+------------------+
| 1 | agency_type1 |
| 2 | some_other_type |
| 3 | agency_type1 |
| 4 | agency_type1 |
| 5 | some_other_type |
+--------+------------------+
I receive the folloing output of my query:
+----------+------+
| p.id | a.id |
+----------+------+
| 1 | 1 |
| 2 | 4 |
+----------+------+
The desired output would be:
+----------+------+
| p.id | a.id |
+----------+------+
| 1 | 1 |
| 2 | 4 |
| 3 | null |
| 4 | null |
+----------+------+
It looks like you don't want to distinguish between an agency which is missing and an agency which is present but the wrong type. So you would want a regular JOIN not a LEFT JOIN for the pa/a pair, and also want to filter out the unwanted type directly on that join. Then you want to do a LEFT JOIN from person to the results of that just-described join.
select p.id p_id, a.id a_id from person p
left join (person_agency pa join agency a on pa.agency_id = a.id and a.type='agency_type1')
on p.id = pa.person_id;
p_id | a_id
------+--------
1 | 1
2 | 4
3 | (null)
4 | (null)
The parenthesis around the join pair are not necessary but I find they make it clearer.
If one person is associated to multiple agencies of the correct type, all of them will be shown. I assume this is what you want, although it was not a scenario covered in your example data.
Try to change left join
to
join (inner join).

SQL - Finding unique values on two tables

I have two tables where I want to find
a. distinct usernames, non-distinct document#, and non-distinct location names
b. distinct usernames, non-distinct document#, and distinct location names
These are two separate sql queries.
Here is what those tables would look like:
User Table
|---------------------------------------|------------|
| UserId | UserName |Document#| LocationId |
|---------------------------------------|------------|
| 1 | bob2# | DL | 1 |
|---------------------------------------|------------|
| 2 | mary3# | Passport| 2 |
|---------------------------------------|------------|
| 3 | bob2# | SIN# | 4 |
|---------------------------------------|------------|
| 4 | sam5# | DL | 3 |
|---------------------------------------|------------|
| 5 | bob2# | SIN# | 1 |
|---------------------------------------|------------|
Location Table
|---------------------------------------|
| LocationId | UserId |LocName |
|---------------------------------------|
| 1 | 1 | Denvor |
|---------------------------------------|
| 2 | 2 | NY |
|---------------------------------------|
| 3 | 3 | San Fran |
|---------------------------------------|
| 4 | 4 | Chicago |
|---------------------------------------|
This is what I've tried, for part a)
select User.UserName, User.Document#, Location.LocName
from User Inner Join
Location
On User.UserId = Location.LocationId
Group by User.UserName
This is for part b)
select User.UserName, User.Document#, Location.LocName
from User Inner Join
Location
On User.UserId = Location.LocationId
Group by User.UserName, Location.LocName
Can someone shed some light as to how to approach this?
You need aggregation with your group by
Example you can group by User.UserName and get number of Documents (Count), and Count of Location.LocName
select User.UserName, Count(User.Document#), Count(Distinct Location.LocName)
from User
Inner Join Location On User.UserId = Location.LocationId
Group by User.UserName
Edit :
I think you are doing the join wrong as you joining User ID to Location ID
It should be
select User.UserName, Count(User.Document#), Count(Distinct Location.LocName)
from User
Inner Join Location On User.LocationId = Location.LocationId
Group by User.UserName

SQL - Join with multiple condition

I'm trying to join my users table with my jobs table based on a mapping table users_jobs:
Here is what the users table looks like:
users
|--------|------------------|
| id | name |
|--------|----------------- |
| 1 | Ozzy Osbourne |
| 2 | Lemmy Kilmister |
| 3 | Ronnie James Dio |
| 4 | Jimmy Page |
|---------------------------|
jobs table looks like this:
|--------|-----------------|
| id | title |
|--------|-----------------|
| 1 | Singer |
| 2 | Guitar Player |
|--------------------------|
And users_jobs table looks like this:
|--------|-------------|-------------|---------------|-------------|
| id | user_id | job_id | column3 | column4 |
|--------|-------------|-------------|---------------|-------------|
| 1 | 1 | 1 | 0 | 1 |
| 2 | 2 | 1 | 1 | 0 |
| 3 | 3 | 1 | 0 | 1 |
| 4 | 4 | 2 | 1 | 0 |
|----------------------|-------------|---------------|-------------|
For example, let's say the ozzy does a query.
Here is what should expect:
|--------|------------------|------------|--------- |
| id | name | column3 | column4 |
|--------|----------------- |------------|----------|
| 1 | Ozzy Osbourne | 0 | 1 |
| 2 | Lemmy Kilmister | 1 | 0 |
| 3 | Ronnie James Dio | 0 | 1 |
|---------------------------|------------|----------|
Basically, he can only see the job in which he is registered (role) and the users included.
I tried to do this:
SELECT u1.*, uj1.colum3, uj1.column4
FROM users AS u1
JOIN users_jobs AS uj1 ON uj1.user_id = 1
JOIN jobs AS j1 ON j1.id = up1.job_id
WHERE uj1.job_id = 1
Any help would be great!
Looks like you need INNER JOIN Try this :
select u.id, u.column3 , u.column4 from users u
inner join user_jobs uj on u.id=uj.user_id
inner join jobs j on j.id=uj.job_id
where uj.job_id=1;
If you need by certain user_id
select u.id, u.column3 , u.column4 from users u
inner join user_jobs uj on u.id=uj.user_id
inner join jobs j on j.id=uj.job_id
where uj.job_id=1
and u.id=1;
I found a solution.
Using #stackFan approach adding an EXISTS clause to make sure that the user is in.
SELECT u.id, u.column3 , u.column4
FROM users u
INNER JOIN user_jobs uj on u.id = uj.user_id
INNER JOIN jobs j on j.id = uj.job_id
WHERE uj.job_id = <job-ID>
AND
EXISTS (
SELECT *
FROM users_jobs AS uj
WHERE uj.job_id = <job-ID>
AND uj.user_id = <user-ID>
);
Try LEFT JOIN. It will display all users, whether they have job or not.
SELECT u.id, u.name, uj.colum3, uj.column4
FROM users AS u
LEFT JOIN users_jobs uj ON uj.user_id = u.id
LEFT JOIN jobs j ON j.id = uj.job_id

SQL query using GROUP_CONCAT() function

I have two tables:
1.Activity-- which stores all the activities from a user
2.User-- which stores all the registered users
I want to fetch all the posts and the likes to all posts in one query. A row is a post or like is decided by the value of type column.
Table Name - Activity
| actId | parentId | type | postedby |
---------------------------------------------------
| 100 | NULL | post | 100 |
| 200 | 100 | like | 200 |
| 300 | 100 | like | 300 |
| 400 | 100 | like | 400 |
| 500 | NULL | post | 100 |
| 600 | 500 | like | 600 |
Table Name - User
| userId | name |
-------------------
| 100 | Amit |
| 200 | Alok |
| 300 | Arjun |
| 400 | Arpeet |
| 600 | Amaan |
The output should be
| actId | name | LikedBy |
------------------------------------------
| 100 | Amit | Alok, Arjun, Arpeet|
| 500 | Amit | Amaan |
NOTE - I don't want this to be achieved using FOR XML PATH since it is not supported in SQLite which I am working on.
My query attempt was
SELECT a.id, u.name,
(select group_concat(u.name) from activity a, user u where a.id = u.id and a.type = 'like'
group by a.parent) as likedby
FROM activity a, user u
WHERE a.id = u.id and a.type = 'post'
The result I got was
| Id | name | LikedBy |
---------------------------------------
| 100 | Amit | Alok, Arjun, Arpeet|
You can see that the other row was missing from result.
Try this:
select t.id4id Id, n1.Name Name, group_concat(n2.name) Groups
from (select t1.actid id4id, t1.postedby id4name, t2.postedby id4groups
from Activity t1 join Activity t2 on t1.actid = t2.parentid) t join "user" n1 on t.id4name = n1.userid join "User" n2 on t.id4groups = n2.userid
group by id4id
Notes: 1. I assume that a post will always have a null value in parent
You do not need a subquery for this. You simply need two joins in order to get the values for the original name and the liked name:
select a.parentid, u.name, group_concat(ul.name separator ', ') as likedby
from activity a join
user ul
on a.postedby = ul.userid join
user u
on a.parentid = u.userid
where a.type = 'like'
group by a.parentid, u.name;

Using inner join twice

Trying to select the Match Table and convert the ID's into the Schools name, but right now I can only get one row to work at a time. What would my select look like instead?
select Match.ID, School, GuestTeamID from Match
inner join Team on team.id = match.HomeTeamID
Match Table
+------------+------------+-------------+
| ID | HomeTeamID | GuestTeamID |
+------------+------------+-------------+
| 1 | 1 | 2 |
| 2 | 3 | 4 |
+------------+------------+-------------+
Team Table:
+----+----------+
| ID | School |
+----+----------+
| 1 | School A |
| 2 | School B |
| 3 | School C |
| 4 | School D |
+----+----------+
Join Team table twice with Match table to fetch school name.
Try this:
SELECT M.ID, t1.School AS HomeSchool, t2.School AS GuestSchool
FROM MATCH m
INNER JOIN Team t1 ON t1.id = m.HomeTeamID
INNER JOIN Team t2 ON t2.id = m.GuestTeamID;