2013-08-31 33 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

的人謝謝。我會嘗試。 –