Pick up messages sent and received from Mysql

Asked

Viewed 257 times

0

I am developing a personal messaging system and I need to list the messages I received and the messages I sent, only that I am having difficulties, because the code I did can only get all that I sent or all that I received and never both. The code I’m using

<?php    
$query = mysql_query("SELECT pr.id_perfil, pr.id_perfil_enviou, pr.recado, pe.nome as NomeEnviou, prm.nome as NomeRecebeu FROM perfil_recados AS pr INNER JOIN perfil AS pe ON pe.id = pr.id_perfil_enviou INNER JOIN perfil AS prm ON prm.id=pr.id_perfil WHERE (pr.id_perfil='961' AND pr.id_perfil_enviou = '15') OR (pr.id_perfil='15' AND pr.id_perfil_enviou = '961')");

while($exe = mysql_fetch_array($query)){                    
   echo 'De: '.$exe['NomeEnviou'].' para '.$exe['NomeRecebeu'];    
}
?>
  • See, so you shouldn’t have two Select’s?? Because you won’t always send, and it will get an answer. In other words, in just a SELECT for me I don’t think it will...

  • 1

    Consider using the UNION clause of SQL. http://blog.tiagopassos.com/2010/07/20/realizando-duas-ou-mais-consultas-com-union-e-union-all-no-mysql/

  • Thank you @Tony o UNION helped me in what I needed!

2 answers

1


Consider using the clause UNION of SQL.

In Mysql the UNION keyword is used to match the result of multiple SELECT commands in a single result.

Example:

example:

(SELECT * FROM clientes WHERE id_cidade = 1 LIMIT 3)
UNION (SELECT * FROM clientes WHERE id_cidade = 5 LIMIT 3)
UNION (SELECT * FROM clientes WHERE id_cidade = 8 LIMIT 3)

Reference: http://dev.mysql.com/doc/refman/5.0/en/union.html

  • 1

    In this case I find UNION ALL more interesting. I do not believe that the data will be repeated and the performance of UNION ALL is superior because it does not need to check for duplicates. Details

0

And if you do so

SELECT pr.id_perfil, 
       pr.id_perfil_enviou, 
       pr.recado, 
       pe.nome AS NomeEnviou, 
       prm.nome AS NomeRecebeu
FROM perfil_recados AS pr 
INNER JOIN perfil AS pe ON pe.id = pr.id_perfil_enviou 
INNER JOIN perfil AS prm ON prm.id = pr.id_perfil 
WHERE pr.id_perfil IN (15, 961) 
   OR pr.id_perfil_enviou = (15, 961);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.