php - 在查询中使用条件语句来查找适合联接和分组依据的列?

标签 php mysql

我正在开发一个私有(private)消息系统,它看起来更像是一个社交网络消息。没有标题,相关的私信显示如论坛主题。

我有两个表来跟踪 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

我可以通过两个查询轻松地编写此内容,一个用于接收者,一个用于发送者 但就像我说的,我不想把它们分开

最佳答案

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

关于php - 在查询中使用条件语句来查找适合联接和分组依据的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10830271/

相关文章:

MySQL子查询返回多行,如何解决?

mysql - 在 MySQL 中运行 .sql 文件

php - 如何让 mysql Group_Concat 使用额外的 CONCAT 信息?

php - 如果 mysql 数据库中的数据发生变化,如何触发 AJAX

php - 如何在不降低加载速度的情况下将 PHP 嵌入 CSS(在 Wp 中)

php - DDD - 在面向文档的存储、PostgreSQL、MongoDB 中存储域对象

php - 从数据库查询发送多封电子邮件

PHP 表单处理未发送正确的电子邮件

PHP 和 mySQL,使用当前日期?

php - fatal error : Call to a member function query() on null