同一MYSQL查询中的父消息和子消息

时间:2016-08-19 10:14:04

标签: php mysql

从上表中我想提取一个包含所有消息的列表,其中parent_id = 0且sender_id或receiver_id等于我的登录ID。

Table:Messages
id | parent_id | sender_id | receiver_id | subject | message | read

这很容易,但我无法弄清楚如何计算消息WHERE parent_id = 0的所有子消息。

我试过了:

$my_messages = mysql_query("
  SELECT

messages.id, messages.sender_id, messages.receiver_id, messages.subject, messages.message, messages.minute,
 messages.hour, messages.day, messages.month, messages.year, COUNT(*) as 'mcount'
    FROM messages 
    LEFT JOIN messages AS mchild ON mchild.parent_id = messages.id 
    WHERE(messages.sender_id='$login_session' or messages.receiver_id='$login_session') 
    and messages.parent_id = '0'
    ORDER BY messages.year DESC, messages.month DESC, messages.day DESC, messages.hour DESC, messages.minute DESC

");

我无法想象的另一件事是如何为每个parent_id计算所有子+父消息= 0如果sender_id = $ login_id则读取= 1,如果receiver_id = $ login_id则读取= 1

以下是一个例子:

Table:Messages
id | parent_id | sender_id | receiver_id | subject | message | read
 1 |         0 | Paul      | John        | Test    | Test    | 0
 2 |         0 | Paul      | Chris       | Test    | Test    | 0
 3 |         1 | john      | Paul        | Test    | Test    | 0
 4 |         1 | Paul      | John        | Test    | Test    | 1
 5 |         1 | John      | John        | Test    | Test    | 0
 6 |         0 | Paul      | Jack        | Test    | Test    | 0

输出:

ID:1 - 4 messages (1 parent+ 3 children), $unread=1 because read = 1 for  ID:4 wich is a child for ID:1
ID:2 - 1 message
ID:6 - 1 message

1 个答案:

答案 0 :(得分:0)

使用自我加入:

SELECT m1.id,
       COUNT(*) AS childCount
FROM messages m1
INNER JOIN
messages m2
    IN m1.id = m2.parent_id
WHERE '$login_session' IN(m1.sender_id,m1.receiver_id)
  AND m1.id = 0 -- you can remove this condition if you want all parents

GROUP BY m1.id

通常,COUNT函数与GROUP BY一起使用,在这种情况下,组是每个父组。但由于你只想要parent_id为零,我将其添加到WHERE子句中,这将过滤掉除此之外的每个组。如果您想了解更多信息,可以将其删除。