7
In my system, there is a system of posts and another of friendships. It follows the structure of tables:
posts: id | usuario | conteudo | data | hora
friendships: id | usuario1 | usuario2 | status
And I’m using the following query to return posts from both the current user and my friends (when status = 2
):
SELECT
postagem.id, usuario, conteudo, data, hora, usuario1, usuario2, status
FROM
postagens postagem
LEFT JOIN
amizades ON usuario = usuario1 OR usuario = usuario2
WHERE
status = 2 OR usuario = Igor
ORDER BY
postagem.id DESC
LIMIT 10
It’s working perfectly, returning both my posts (logged-in user) and those of my friends (user-to-user relationship where status = 2
), and here is an example of data contained in the table amizades
:
2 | Igor | Joao | 2
1 | Lucas | Igor | 0
In the above data, when status = 2
means they’re friends, and when status = 0
means they’re not friends.
However, as there is my user (Igor) in the two rows of the table, it duplicates the posts of such user, that is, if there was another row in the table, of which would make the relationship of friendship between my user and any other, would triple the posts. How to solve this?
You are passing the user by id?
– Sr. André Baill
@Andrébaill in fact, where he is
usuario = Igor
isusuario = '$usuario'
, I just altered it so you can better understand my problem.– Igor
Yes, but is the user id or user name? you would have to pass the id_user if it is not
– Sr. André Baill
That’s the same name...
– Igor
You have to pass the ID in order to use the left Join correctly.
– Sr. André Baill
SELECT * FROM posts AS C1 LEFT JOIN friendships AS C2 USING(id_usuario)
– Sr. André Baill
But why can’t it be by name? That username would be like an id, it’s unique
– Igor
Because every time you relate or change the user name, it will not be able to authenticate, and also for security and still for issues just like this one that you posted, of relationship tables :)
– Sr. André Baill
There is no way to change the username, after registering, cannot be changed
– Igor
beauty then...
– Sr. André Baill
Anyway, how to do? I tried to replace the
ON
forUSING
just like you said, but it didn’t work... You could give an example of the query and how it would look?– Igor