2014-03-03 69 views
0

T1:MySQL查詢用於獲取字段的值作爲計算

+--------------+------------------+------+-----+---------+----------------+ 
    | Field  | Type    | Null | Key | Default | Extra   | 
    +--------------+------------------+------+-----+---------+----------------+ 
    | id   | int(11) unsigned | NO | PRI | NULL | auto_increment | 
    | message_text | text    | NO |  | NULL |    | 
    | sender_id | int(11) unsigned | NO | MUL | NULL |    | 
    | receiver_id | int(11) unsigned | NO | MUL | NULL |    | 
    | pair_id  | int(11) unsigned | NO | MUL | NULL |    | 
    | time_stamp | bigint(20)  | NO |  | NULL |    | 
    | is_read  | tinyint(1)  | NO |  | 0  |    | 
    +--------------+------------------+------+-----+---------+----------------+ 

T2:

+----------------+------------------+------+-----+---------+----------------+ 
    | Field   | Type    | Null | Key | Default | Extra   | 
    +----------------+------------------+------+-----+---------+----------------+ 
    | id    | int(11) unsigned | NO | PRI | NULL | auto_increment | 
    | user_id1  | int(11) unsigned | NO | MUL | NULL |    | 
    | user_id2  | int(11) unsigned | NO | MUL | NULL |    | 
    +----------------+------------------+------+-----+---------+----------------+ 

我想從這個表像取記錄:

pair_id | message_text | sender_id | receiver_id | count_unread 

table(T1)店其中的訊息:

message_text: message, 
    sender_id: sender, 
    receiver_id: receiver, 
    pair_id: This is the foreign key referring to an other table that keeps the chatting user pairs     i.e. T2, 
    is_read: 0 if unread, otherwise 1. 

現在,我想要所有的對與相應的未讀消息計數。此外,即使計數爲零,也必須顯示該對。提前致謝。

查詢我曾嘗試:

SELECT all_messages.id, 
      all_messages.sender_id, 
      all_messages.receiver_id, 
      count(all_messages.id) AS unread_msg_count 
     FROM all_messages 
      JOIN message_pairs 
       ON message_pairs.id = all_messages.pair_id 
    WHERE all_messages.receiver_id = :receiver_id 
      AND is_read = 0 
    GROUP BY 
      pair_id 
+0

你嘗試編寫一個查詢? – MikkaRin

+0

是啊試過,但沒有得到預期的結果。 – Arbind

+0

可能你會告訴我們你嘗試了什麼? – MikkaRin

回答

1

您不能列出消息內容在同一關係,你正在使用用於計數的一個,因爲如果算上然後一行對應於一對許多消息。

你可以指望這樣的:

SELECT message_pairs.*, 
      count(all_messages.id) AS unread_msg_count 
     FROM all_messages 
      RIGHT JOIN message_pairs 
       ON message_pairs.id = all_messages.pair_id 
    WHERE is_read = 0 
    GROUP BY 
      message_pairs.*;