If I understand well the meaning of the fields in the tables you can get so:
select u.usuario_id as idUsuario,
u.nome as nomeUsuario,
a.id_remenente as idAmigo,
a.sao_amigos as IndicadorDeAmigo,
p.post_id as idDoPost
from usuario as u
inner join amizades as a on u.usuario_id = a.id_destinatario
inner join posts as p on a.id_remenente = p.id_autor
where u.usuario_id = 1
and a.sao_amigos = 1
I did the join
of all tables considering that you want to pick up posts that a friend sent to the logged in user, then:
All users join
with friendships where the logged-in user is the recipient of the post u.usuario_id = a.id_destinatario
Making Join with post where the sender of the message (user’s friend logged that sending the message) is the owner of the post a.id_remenente = p.id_autor
Filtering all of the logged-in user 1
and who is a friend (a.sao_amigos = 1
)
Here the Fiddle with it working.
No Fiddle Ricardo is the logged in user, Daniel and Felipe sent posts to him, but only Daniel is a friend, so only the post Daniel appeared.
UPDATING
According to the comment, you can do so: (Fiddle)
select *
from posts
where id_autor in
(select id_destinatario
from amizades
where id_remenente = 1
and sao_amigos = 1)
union
select *
from posts
where id_autor in
(select id_remenente
from amizades
where id_destinatario = 1
and sao_amigos = 1)
Grab all posts from a user who has received a friend request from the logged in user and confirmed plus all posts from a user who submitted a request to the logged-in user and the user accepted.
How do you identify if you are friends? In the friendship table has a field but it is int and not boolean.
– user28595
I use 0 or 1
– Salomão Neto
What is the relationship between the user and friendships? O
id_usuario
is like a field in friendships?– Ricardo
@Richard apparently, destination id and sender id are user ids.
– user28595