4
I am currently using the following query
to select all saved posts in the database: "SELECT * FROM postagens ORDER BY id DESC LIMIT 7"
, however, I want to select only the posts made by "friends".
The relationship of friendships is in the table amizades
, where when you’re friends, the column status = 2
. How to list both tables to select all posts made by "friends"?
What I got so far:
SELECT
postagem.id, postagem.usuario, postagem.conteudo, postagem.data, postagem.hora,
amizade.usuario1, amizade.usuario2, amizade.status
FROM
postagens postagem
LEFT JOIN
amizades amizade ON postagem.usuario = amizade.usuario2
WHERE
amizade.status = 2
ORDER BY
postagem.id DESC
LIMIT 10
However, I want to select all posts made by me and also by my friends (when amizade.status = 2
), And then I’m failing, I don’t know how to select just my friends' posts and mine as well, because only mine appear.
Columns:
posts:
id | usuario | conteudo | data | hora
friendships:
id | usuario1 | usuario2 | status
I just read the answer of the link, and I understood that I will have to use INNER JOIN, but I do not know how to adapt to my case, since they are different cases. Could you give me an example? @Bacco
– Igor
@Bacco worked perfectly, my mistake was in not using the
OR
within theON
to compare both users, however, there is another problem. If there is no friendship withstatus = 2
no post is shown, and the correct thing would be to show my posts regardless of whether you have any friends or not. How to tidy up?– Igor
@Bacco if you would like to have a look... http://answall.com/questions/99611/problema-com-l%C3%B3gica-ao-usar-left-Join/
– Igor
Put the script for creating the 2 tables.
– William Okano
If you only want the results that are in the two tables do not use LEFT JOIN use INNER JOIN. LEFT will continue to bring all the data, but in the return of SQL the data referring to friendship table will be null when it is possible to relate the post to friendship, (but even so bring the posts).
– Sileno Brito