0

各ユーザーの通知数を見つけようとしていますが、少し問題があります。クエリが必要なものに完全に機能していたので、テーブルを少し変更しました。

作業クエリ:

$numNotifications = mysql_num_rows(mysql_query("
SELECT  
      N.*, 
      P.*
      FROM 
          notifications N, 
          posts P
      WHERE 
          N.userID='$session' 
      AND 
          (
          N.action='1' OR N.action='2'
          ) 
      AND 
           N.uniqueID=P.id AND  P.state='0'"
));

ただし、uniqueID は一部の行で異なります。N.aciton が「1」の場合、N.uniqueID を P.id と比較する必要がありますが、N.action が「2」の場合、そのテーブルの行を P.id と比較する必要があります。

クエリの例 (動作する必要がありますが、動作しません)

$numNotifications = mysql_num_rows(mysql_query("
SELECT  
      N.*, 
      P.*, 
      C.*, 
     (CASE WHEN (
                  N.action = 2 AND N.state = 0
                 )
            THEN 
                 C.postID ELSE N.uniqueID END
      ) AS postId  
      FROM 
          notifications N, 
          posts P, 
          comments C 
      WHERE 
          N.userID='$session' 
      AND 
          (
          N.action='1' OR N.action='2'
          ) 
      AND 
           postId=P.id AND  P.state='0'"
));

私の3つのテーブル構造の図:

http://i41.tinypic.com/nyzolg.png

4

1 に答える 1

1

どうぞ :)

SELECT
    COUNT(`notif_id`) AS `number_of_new_notifications`
FROM
    (
        SELECT
            `notifications`.`id` AS `notif_id`
        FROM
            `notifications`
        JOIN
            `posts`
        ON
            `notifications`.`uniqueID`=`posts`.`id`
        WHERE
            `notifications`.`userID`='$session'
        AND
            `notifications`.`action`=1
        AND
            `notifications`.`state`=0
        AND
            `posts`.`state`=0
        UNION ALL
        SELECT
            `notifications`.`id` AS `notif_id`
        FROM
            `notifications`
        JOIN
            `comments`
        ON
            `notifications`.`uniqueID`=`comments`.`id`
        JOIN
            `posts`
        ON
            `comments`.`postID`=`posts`.`id`
        WHERE
            `notifications`.`userID`='$session'
        AND
            `notifications`.`action`=2
        AND
            `notifications`.`state`=0
        AND
            `comments`.`state`=0
        AND
            `posts`.`state`=0
    ) AS notification_ids;
于 2012-01-08T23:19:14.430 に答える