MySQL inner join with 2 columns - mysql

I have one table users with 2 fields : id , name and another table friends with 2 fields : userid1 userid2 .
So this means userid1 is friend with userid2 . I want , with one inner or left join to show this :
userid1 name(got from users table) is friend with userid2 name(got from users table)
something
SELECT * FROM friends INNER JOIN users ON friends.userid1 = users.id AND friends.userid2 = users.id but this is not working.
Any good query with good explanation please?
If, for example I have the next details in the users table :
ID : 1 NAME : FinalDestiny
ID : 2 NAME : George
and the next details in the friends table :
ID1 : 1 ID2 : 2
So this means 1 is friend with 2.
I need with one query to get the name of 1 and the name of 2 and to echo that they're friends
FinalDestiny is friend with George

I know that you specify that you want this done with one join, but it looks to me like you need two. I believe this query will give you what you need:
SELECT u1.Name, u2.Name
FROM Users u1, Users u2, Friends f
WHERE u1.id = f.userid1 AND u2.id = f.userid2
I am joining the Users table with the Friends table with on Users.id = Friends.userid1. Then, I am joining this new table with the Users table on (new table).userid2 = Users.id. This results in a table with 4 columns. These columns are the original 2 columns of the Friends table in addition to 2 columns for the names of the friends. u1, u2, and f and referring to the three tables that were joined. The users table was joined with the friends table twice. u1 is the copy of the Users table that was joined on Friends.userid1 = User.id. u2 is the copy of the Users table that was joined on Friends.userid2 = User.id.
From this table with 4 columns, I am selecting only the names of the friends.
Let me know if more explanation is needed.

You check on a user being a friend of itself. Use OR in your select to match user's friends:
SELECT * FROM friends INNER JOIN users ON friends.userid1 = users.id OR friends.userid2 = users.id

If, for example I have the next details in the users table :
ID : 1 NAME : FinalDestiny
ID : 2 NAME : George
and the next details in the friends table :
ID1 : 1 ID2 : 2
So this means 1 is friend with 2.
I need with one query to get the name of 1 and the name of 2 and to echo that they're friends
FinalDestiny is friend with George

Related

How to find out results for not matching particular condition in SQL from multiple tables?

I have 3 tables :
Person table stores basic person wise details with ID as primary Key
This person can have relationships (father / mother etc), which are saved in Relationship table, however the users for them are created in Person table (e.g. ID = 2,3 in person table), This way we know that 2,3 are related to user 1 (carry).
We also have 3rd table - address, which store user ID wise addresses.(for both a user and his related persons, who are also users)
I want to find out if an address exists for either a user or for his related users in SQL. How to achieve this ?
You can combine two rules and search on the combined table as below
SELECT * FROM
(
SELECT username,id,Address.Address
FROM Person
INNER JOIN Address ON Person.id = Address.Userid
UNION ALL
SELECT username,id,Address.Address
FROM Person
INNER JOIN Relationship ON Relationship.Relatedid = Person.id
INNER JOIN Address ON Relationship.Userid = Address.Userid
) as RES
WHERE Address = 'xyz road'
Also you can find DBFiddle link to workout
Query:
select p.id,p.username,(case when a.userid is null then 'No' else 'Yes'end) IsAddressAvailable
from Person p
left join Address a on p.id=a.Userid
Output:
id
username
IsAddressAvailable
1
Carry
Yes
2
Carry-Father
No
3
Carry-Mother
Yes
db<fiddle here

SQL INNER JOIN only returns the first result

I have a Many to Many relationship between Pets and Users, with a UserPets join table. I've been trying to write an SQL query that would return the user name with the amount of times walked. However, I've only been able to return a user and a timesWalked and they are not even the associated ones.
The current SQL statement I have is:
SELECT user_pets.timesWalked, users.name
FROM user_pets
INNER JOIN users ON user_pets.user_id = users.id
And the returned result is:
[{"timesWalked"=>20, "name"=>"user1", 0=>20, 1=>"user1"}]
In this instance, user1 is not the one that walked the dog 20 times, which is the association I need.
table name: users
name
user1
user2
user3
table name: user_pets
name timesWalked userId petId
usep1 10 2 1
usep2 20 1 3
usep3 5 1 2
table name: pets
name
pet1
pet2
pet3
My expected result is:
[{"timesWalked"=>20, "name"=>"user1"}]
[{"timesWalked"=>10, "name"=>"user3"}]
[{"timesWalked"=>5, "name"=>"user2"}]
In this instance, the user name from the User's table is being associated with timesWalked from the user_pets table
How can I return all the timesWalked with all the user names who walked the pet?
You can use inner join to achieve this.
Below query lists all the users who have walked all the pets for total number of time.
i.e. User 1 has walked two pets for 2 times each.
select
up.timesWalked, u.name as UserName, p.name as PetName
from user_pets up
inner join users u on up.user_id = u.id
inner join pets p on up.pet_id = p.id
Have a look at this fiddle : http://sqlfiddle.com/#!17/c91a1/2

SQL find records based on two columns

Given a users table with primary key of id, I have a foreign table called friends which only has two fields (userid1, userid2). This allows us to create any kind of relationship between different users (one to many, one to one, etc). A user can appear in either column and both columns are equal. IOW, a single entry per relationship.
How can I pull all of the friends that a given user id has. Say Jonny, has 3 friends and his user id is 16... should my sql query look like this?
SELECT *
FROM db.users
JOIN db.friends
ON db.users.id = db.friends.userid1
AND db.users.id = 16
Hopefully, this is clear. Also, if possible, can I exclude Jonny from the result set?
This query, as listed gies me the following:
id name uuid birthday userid1 userid2
16 jonny ABCDEFGHIJKLMNOP 1967-04-27 01:00:00 1 2
16 jonny ABCDEFGHIJKLMNOP 1967-04-27 01:00:00 1 3
This is pretty close, except I want his friends, not jonny
Thanks guys, so I got it to work thanks to you. Here is the final working query.
SELECT *
FROM db.users
WHERE db.users.id IN
(
SELECT db.friends.userid2 as id FROM db.friends WHERE db.friends.userid1 = 16
union
SELECT db.friends.userid1 as id FROM db.friends WHERE db.friends.userid2 = 16
)
which gives me:
id name uuid birthday
2 robin ABCDEFGHIJKLMNOP 1967-04-27 01:00:00
3 gary ABCDEFGHIJKLMNOP 1967-04-27 01:00:00
You could do a sub query like:
SELECT *
FROM users
WHERE id IN
(
SELECT userid2 as id FROM db.friends WHERE userid1 = 16
)
Add the condition for the user.id to your where clause at the end:
Select * From users
INNER JOIN friends on
users.id = friends.userid1
Where users.id = 16
Also, I would use an Inner Join which will return all records from users only where there is a match in friends
You should filter on the friends table, not the users table.
SELECT friends.*
FROM friends
INNER JOIN users
ON friends.userid2 = users.id
WHERE friends.userid1 = 16
If you just need the friend ID's then there is not reason to join at all
SELECT userid2
FROM friends
WHERE userid1 = 16
You need a list of friends ids:
SELECT U
FROM DB.USERS U
WHERE U.ID IN ( SELECT F.USERID2 FROM DB.FRIENDS F WHERE F.USERID1 = 16)

Single Row Friendship Database Schema with getting userid from one column or the other

I need help querying the friendID from a table.
My table stores the user id of two members who are friends together.
But in order to store a "friendhship" b/w two members I would have to store two records like this:
friendshipID | userID | friendID
1 | 5 | 10
2 | 10 | 5
Yet, that seems heavy for the DB when we really only need to store the first record as that is sufficient as it contains both ids of both members.
However, the trouble comes when I want to query the records of the friends of ID=5. Sometimes the ID is in the userID column and other times it is in the friendID column.
This is the query I am using:
SELECT *
FROM friends
WHERE userID = '5'
OR friendID = '5'
But what I want to do is something like this
SELECT
if $userID=5 then userID as myfriend
else friendID=5 then friendID as myfriend
FROM friends WHERE userID='5' OR myfriendID='5'
Hope that makes sense. In the end I would like to have all the friends ID's of member #5 and not bring up results with #5 as the friend or user....but just his friends.
This query would return the Id value, and name, of the friends of #5 as shown in this SQL Fiddle Example
SELECT f.FriendId AS FriendId
, u.Name AS FriendName
FROM FriendTable AS f
INNER JOIN UserAccount AS u ON f.FriendId = u.UserId
WHERE f.UserId = 5
UNION
SELECT f.UserId AS FriendId
, u.Name AS FriendName
FROM FriendTable AS f
INNER JOIN UserAccount AS u ON f.UserId = u.UserId
WHERE f.FriendId = 5
The UNION will remove duplicates, making this query work for both a single record of friends, or the 2 record friendship you mention in the comment. You shouldn't need the 2 record friendship though, because there is no new information being stored in the second record that you cannot get from only having one record.

mysql query help to find mutual friends on social networking site

I have a database table called users with a primary key of user_id for each user.
I also have a table called friends with two fields, user_id and friend_user_id.
The user_id field is always the lowest of the two user_id's in order to avoid duplicate entries.
Say I have two users in mind, (lets say user id 1 and user id 4 although they could be anything).
How would I return all rows from the users table for users that are friends with user 1 and user 4 (i.e mutual friends)?
I will give you the recipe:
Find all friends of user 1
Find all friends of user 2
Intersect them and the result will be the mutual friends.
Much like this:
UPDATE: Here's the query:
select f.friend_user_id from friends f where f.friend_user_id in (
select friend_user_id from friends where user_id=<id_of_user_a>)
and f.user_id=<id_of_user_b>
The ids returned by above query will be the id of all the users that are mutual friends of user_a and user_b. If you want to get all the details (name, etc) about those users, then do this:
select f.friend_user_id,u.* from friends f inner join users u
on u.user_id=f.friend_user_id
where f.friend_user_id in (
select friend_user_id from friends where user_id=<id_of_user_a>)
and f.user_id=<id_of_user_b>
SELECT friends.friend_user_id FROM user, friends
INNER JOIN friends ON friends.user_id = user.user_id
WHERE user.user_id = 1
AND friend.friend_user_id
IN (SELECT friends.friend_user_id
FROM user, friends
INNER JOIN friends ON friends.user_id = user.user_id
WHERE user_id = 4)