2013-08-31 31 views
1

我试图从下表中查询sql。我尝试了很多方法来完成工作,但似乎对于我来说找到解决方案太复杂了。内部有4个条件的复杂sql语句

user_id =“200”; // let's说,用户ID现在是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 
------------------------------------------------------------------------------------ 

什么我正尝试做的是配合查询与上面的USER_ID其中只有一个表。 它可以是表中的user_one或user_two。如果user_id在表中是user_one,那么user_one_delmsg不能是“Y”。或者如果user_id是在表user_two然后,user_two_delmsg绝不能“Y”

我曾尝试:

$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 

    } 
    } 

我得到的是: 阵列结果的匹配是查询。 我要的是只有一个that's最大的c_id结果和USER_ X _delmsg绝不能“Y”

我也只能使用取();我没有得到我想要的。 我也在最后的查询中放了限制1,但它没有帮助。

+0

你想要的结果是什么?是3吗?列'c_id'的类型是什么? – bansi

回答

0

为定UserID,尝试

Select Max(c_id) from conversation 
Where 200 in (user_one_id, user_two_id) 
    And (user_one_id <> 200 Or user_one_delmsg <> 'Y') 
    And (user_two_id <> 200 Or user_two_delmsg <> 'Y') 

所有用户ID,请尝试:

Select userId , Max(cid) From 
(Select c_id cid, user_one_id userId 
    from conversation 
    Where user_one_delmsg <> 'Y' 
    Union 
    Select c_id cid, user_two_id userId 
    from conversation 
    Where user_one_delmsg <> 'Y') Z 
Group By UserId 
+0

我也不工作:S你认为是因为pdo? 我已将200取代为$ user_id –

+0

当我将Max取出时,它工作正常!但它没有给我最高ID:S –

+0

你在那里用Max()在哪里得到了什么错误?这就是顶级ID。 –

0

这将选择max(c_id)并将检查user_one_delmsg不等于y。

select max(c_id), user_one_id from conversation where user_one_delmsg!='y'; 

这将选择最大值(C_ID),用于既user_one_id和user_two_id(特别是200所述)和将检查user_one_delmsg。

select max(c_id), user_one_id from conservation where user_one_id='200' and 
user_one_delmsg!='y' union select max(c_id), user_two_id from conservation where 
user_two_id='200' and user_two_delmsg!='y'; 
+0

嗨,谢谢你的回答,它不起作用:S –

+0

@PoramatFin ok,但是请编辑你的问题并提供所需的输出,这对其他人会有所帮助。 – user1502952

0

尝试使用下面的查询

SELECT MAX(c_id) FROM tb_conversation 
    WHERE (user_one_id=200 AND user_one_delmsg='N') 
     OR (user_two_id=200 AND user_two_delmsg='N') 

检查这个Fiddle

+0

的人谢谢。我会尝试。 –