Saturday, 31 August 2013

Complicated sql statement with 4 conditions inside

Complicated sql statement with 4 conditions inside

I´m trying to query the sql from the table below. I have tried many ways
to get the job done.But seemed like it too complicate for me to find the
solution.
user_id="200"; // let´s say the user id now is 200.
tb_conversation
-------------------------------------------------------------------------------------
c_id | user_one_id | user_two_id | user_one_delmsg |
user_two_delmsg
-------------------------------------------------------------------------------------
001 | 200 | 198 | Y | N
------------------------------------------------------------------------------------
002 | 195 | 200 | Y | N
------------------------------------------------------------------------------------
003 | 200 | 193 | N | N
------------------------------------------------------------------------------------
What I´m trying to do is to query the only one table which match with the
user_id above. And it can be user_one or user_two in the table. if the
user_id is user_one in the table then, user_one_delmsg must not be "Y". OR
if the user_id is user_two in the table then, user_two_delmsg must not be
"Y"
What I have tried :
$q= "SELECT * from conversation ORDER BY c_id DESC ";
$_stmt = $conn->prepare($q);
$_stmt->execute();
$row=$_stmt->fetchAll();
foreach ($row as $r) {
if ($user_id==$r['user_one_id']){
if ( $r['user_one_delmsg']!="Y") {
//do something
}
}
if ($user_id==$r['user_two_id']){
if ( $r['user_two_delmsg']!="Y") {
//do something
}
}
What I get is: array of result that match the query. But what I want is
only one result that´s the max c_id and user_x_delmsg must not be "Y"
I have also use only fetch(); I did not get what I want. I have also put
the limit 1 in the last of query, but it did not help.

No comments:

Post a Comment