MYSQL连接两个表和CASE WHEN

时间:2012-02-06 16:23:29

标签: php mysql join

我无法解决这个问题:

SELECT * 
FROM usersActivity 

(JOIN friends ON  usersActivity.userID=friendID
   CASE WHEN friends.userID=$session 
   THEN friends.userID2 
   ELSE friends.userID 
   END AS friendID 

   WHERE (friends.userID=friendID AND friends.userID2=$session) 
   OR (friends.userID=$session AND friends.userID2=friendID)
 )
WHERE usersActivity.setActivity!=3 
AND usersActivity.userID!=$session
ORDER BY usersActivity.setActivity ASC

我希望根据您与谁的朋友在线返回谁。 目前我必须这样做才能让它做我想做的事情:

$onlineUsers = mysql_query("
SELECT *
FROM usersActivity 
WHERE setActivity!=3 
AND userID!=$session
ORDER BY setActivity ASC
");

while($users = mysql_fetch_array($onlineUsers))
{
$friendID = $users['userID'];
$friend = mysql_fetch_assoc(mysql_query("
   SELECT 
   CASE WHEN userID=$session 
   THEN userID2 
   ELSE userID 
   END AS friendID 
   FROM friends 
   WHERE (userID=$friendID AND userID2=$session) 
   OR (userID=$session AND userID2=$friendID)"));

   if($friendID==$friend['friendID'])
   {
          print $friendID; //userID that is online
       }      
 }

0 个答案:

没有答案