在查询中使用条件语句来查找适当的连接列和分组依据?

时间:2012-05-31 08:50:50

标签: php mysql

我正在开发一个私人消息系统,它看起来更像是社交网络消息。没有标题和相关的pms显示为论坛帖子。

我有两张表来记录pms

pm_sessions  : pm_session  , sender , receiver, pm_counter 

pm           : id , pm_session  , text , date , sender

pm_session就像pm的包装器

现在在用户个人资料中我想显示当前用户发送或接收pm的用户列表

问题是我不想单独显示接收者和发送者用户,我想让所有在一个列表中与我的家伙交谈的用户

这是我想到的,现在它对所有IF语句都不起作用

$current_user = $_session['userid'];
    $query = " 

 select pms.sender , pms.receiver, 
 count(pms.otheruser) as total_dialogs_with_this_user , 
 u.username as other_user_name  , u.id as other_user_id

 from pm_session pms

   //// joining to the users table on the other user id
   if($current_user = pms.sender)
     JOIN users u on pms.receiver= u.id 
   if($current_user = pms.receiver)
     JOIN users u on  pms.sender = u.id 

  WHERE pms.reciver = $current_user || pms.sender = $current_user

   /// grouping by other user id
   if($current_user = pms.sender)
     group by pms.receiver
   if($current_user = pms.receiver)
     group by pms.sender ";

我希望结果类似于

HELLO max ... you have been talking to :

ross... 3 dialogs
joey ... 4 dialogs
chandler ... 5 dialogs

我可以轻松地用两个查询来写这个,一个用于接收器,一个用于发送者  但就像我说我不想分开它们

1 个答案:

答案 0 :(得分:2)

SELECT   CASE $current_user
           WHEN pms.sender   THEN pms.receiver
           WHEN pms.receiver THEN pms.sender
         END                  AS other_user_id,
         u.username           AS other_user_name,
         COUNT(pms.otheruser) AS total_dialogs_with_this_user
FROM     pm_session           AS pms
  JOIN   users                AS u
           ON u.id = CASE $current_user
             WHEN pms.sender   THEN pms.receiver
             WHEN pms.receiver THEN pms.sender
           END
GROUP BY other_user_id, other_user_name