Question

I have this query in sql, and i can't get it right.

I'm trying to make a query to get the results from chat.

select message, first_name, last_name, dataPost,picture 
from chat_comms 
right join utilizadores 
           on (chat_comms.id_writer = utilizadores.id_user) 
               or (chat_comms.id_reader =  utilizadores.id_user) 
where id_writer = 1 
or (id_reader = 1 and id_writer = 13) 
order by dataPost ASC

RESULT

enter image description here

the first_name, last_name, picture, should be different because they are different users, how can i solve this?


SQL FIDDLE:

VIEW SQL FIDDLE


Was it helpful?

Solution

It looks like you have the duplicate rows because one of the users is the "writer" and the other is the "reader". I'm guessing that you actually want one row for each row in chat_comms linked to both the "writer" and "reader". In this case you need to join to utilizadores twice instead of using the or:

select message, writer.first_name, writer.last_name, dataPost, picture 
from chat_comms 
left join utilizadores writer on chat_comms.id_writer = writer.id_user
left join utilizadores reader on chat_comms.id_reader = reader.id_user
where id_writer = 1 
or (id_reader = 1 and id_writer = 13) 
order by dataPost ASC

This is just a guess because you haven't adequately described the result you're trying to achieve.

OTHER TIPS

please verify below mentioned query:

SELECT message, first_name, last_name, dataPost,picture
FROM chat_comms
RIGHT JOIN utilizadores
       ON chat_comms.id_writer = utilizadores.id_user
       OR (chat_comms.id_reader =  utilizadores.id_user)
WHERE id_writer = 1
order by dataPost ASC

Hope that helps, thanks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top