1

以下の表からSQLをクエリしようとしています。仕事を終わらせるために多くの方法を試しましたが、解決策を見つけるには複雑すぎるように思えました。

user_id="200"; // 今のユーザー 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

    }
    }

私が得るのは 、クエリに一致する結果の配列です。 しかし、私が欲しいのは、最大 c_id と user_ x _delmsg が「Y」であってはならない1 つの結果だけです。

また、fetch(); のみを使用しています。私は欲しいものを手に入れませんでした。また、クエリの最後に制限 1 を設定しましたが、役に立ちませんでした。

4

3 に答える 3

0

これは max(c_id) を選択し、y と等しくない user_one_delmsg をチェックします。

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

これにより、user_one_id と user_two_id の両方に max(c_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';
于 2013-08-31T16:25:51.837 に答える
0

特定のユーザーIDについて、試してください

 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')

すべての UserId について、次を試してください。

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
于 2013-08-31T16:31:29.280 に答える