加入 - 使用与COUNT

时间:2016-06-06 12:52:57

标签: php mysql sql join pdo

我有一个聊天系统。有3个表:

data_chats - 保存聊天记录的ID。您可以在此处将聊天标记为已删除。

data_chat_parties - 保留聊天中包含的成员或团队ID以及聊天权限,受邀者等等

data_chat_messages - 保留聊天的实际消息

根据我的查询,我正在尝试从请求此信息的一方(即当前登录的用户)获取与data_chat_parties相关的信息,但也获取聊天中的聊天方总数。

  SELECT
    data_chats.id AS chat,
    data_chats_parties.*,
    COUNT(data_chats_parties.id) AS total_parties,
    data_chats_messages.created AS last_message_created,
    data_chats_messages.author AS last_message_author,
    data_chats_messages.author_type AS last_message_author_type,
    data_chats_messages.message AS last_message
  FROM data_chats
   LEFT JOIN data_chats_parties ON data_chats_parties.chat=data_chats.id
   LEFT JOIN data_chats_messages ON data_chats_messages.chat=data_chats.id AND data_chats_messages.active=1
  WHERE
    data_chats.active=1 AND
    data_chats_parties.member=1 AND
    data_chats_parties.status >= 1
  GROUP BY data_chats_parties.chat
  ORDER BY last_message_created DESC

这一切都运行正常,但total_chat_parties总是返回1,大概是因为它只匹配data_chats_parties.member=1的记录。我如何获取特定于此用户的聚会记录,但同时获取此聊天的参与方总数?

2 个答案:

答案 0 :(得分:2)

您应该使用相关查询:

  SELECT data_chats.id AS chat,
         (SELECT COUNT(data_chats_parties.id) FROM data_chats_parties
          WHERE data_chats_parties.chat = data_chats.id) AS total_parties,
         data_chats_messages.created AS last_message_created,
         data_chats_messages.author AS last_message_author,
         data_chats_messages.author_type AS last_message_author_type,
         data_chats_messages.message AS last_message
    FROM data_chats
    LEFT JOIN data_chats_messages
      ON data_chats_messages.chat = data_chats.id
     AND data_chats_messages.active = 1
     AND data_chats_parties.member = 1
     AND data_chats_parties.status >= 1
   WHERE data_chats.active = 1
   ORDER BY last_message_created DESC

另一件事是WHERE子句的条件,你可以过滤RIGHT子句中LEFT JOIN的{​​{1}}表,这些条件只应在WHERE条款。

您还可以按ON表中的列进行分组 - 根本不建议这样做!使用内部联接或使用其他字段分组。

答案 1 :(得分:1)

您可以在select语句中使用子查询来为您提供所需的计数。

(select COUNT(data_chats_parties.id) from data_chats_parties where data_chats_parties.chat=data_chats.id) AS total_parties,

然后你可以删除行

LEFT JOIN data_chats_parties ON data_chats_parties.chat=data_chats.id

希望我输入的所有内容都正确=)