2014-04-08 11 views
2

問題從信息表中獲取最新的「角色轉換」時間戳

我期待在試圖獲得最低的時間戳(最早)的「面」的票談話更改後,看自第一次回覆最新消息以來已經過去多久了。

例子:

A (10:00) : Hello 
A (10:05) : How are you? 
B (10:06) : I'm fine, thank you 
B (10:08) : How about you? 
A (10:10) : I'm fine too, thank you <------ 
A (10:15) : I have to go now, see you around! 

現在我所尋找的是箭頭指示的消息的時間戳。對話'方'之後的第一條消息發生了變化,在這種情況下,從用戶到支持。從表

示例數據 「消息」:

mid conv_id uid created_at message       type 
2750 1   3941 1341470051 Hello        support 
3615 1   3941 1342186946 How are you?      support 
4964 1   2210 1343588022 I'm fine, thank you    user 
4965 1   2210 1343588129 How about you?     user 
5704 1   3941 1344258743 I'm fine too, thank you   support 
5706 1   3941 1344258943 I have to go now, see you around! support 

我迄今爲止嘗試:

select 
n.nid AS `node_id`, 
(
    SELECT m_inner.created_at 
    FROM messages m_inner 
    WHERE m_inner.mid = messages.mid AND 
    CASE 
     WHEN MAX(m_support.created_at) < MAX(m_user.created_at) THEN -- latest reply from user 
      m_support.created_at 
     ELSE 
      m_user.created_at 
    END <= m_inner.created_at 
    ORDER BY messages.created_at ASC 
    LIMIT 0,1 
) AS `latest_role_switch_timestamp` 
from 
node n 
left join messages m on n.nid = messages.nid 
left join messages m_user on n.nid = m_user.nid and m_user.type = 'user' 
left join messages m_support on n.nid = m_support.nid and m_support.type = 'support' 
GROUP BY messages.type, messages.nid 
ORDER BY messages.nid, messages.created_at DESC 

首選結果:

node_id latest_role_switch_timestamp 
1   1344258743 

但是,這沒有產生任何結果s的子查詢。我正在尋找正確的方向還是應該嘗試其他方法?我不知道這是否可能在MySQL中。

此外,它使用子查詢,出於性能方面的原因,這並不理想,因爲此查詢可能會用於概覽,這意味着它將不得不在概覽中爲每條消息運行子查詢。

如果您需要了解更多信息,請告訴我,因爲我在我束手無策

+0

沒有「conversation_id」列嗎?消息表是否存儲了一個巨大的對話? – Bohemian

+0

啊,我的錯誤,我會編輯主帖以反映細節,有一個conversation_id。感謝您指出 – Magikaas

+0

好的,下一個問題。你想在一個查詢中對每個對話進行最後一次更改嗎?只是確認你不想整行,只是時間戳? – Bohemian

回答

1

將表與自身的最大最新彙總得到最後塊的消息,然後使用MySQL的特殊基的由支撐從那些每個對話挑第一行:

select * from (
select * from (
    select m.* 
    from messages m 
    join (
    select conv_id, type, max(created_at) last_created 
    from messages 
    group by 1,2) x 
    on x.conv_id = m.conv_id 
    and x.type != m.type 
    and x.last_created < m.created_at) y 
order by created_at) z 
group by conv_id 

這將返回整個行,這是最後的塊的第一消息。

請參閱SQLFiddle

性能會相當不錯,因爲沒有相關的子查詢。

+0

哇,看起來很複雜,我得看看在這之後它是如何工作的。我會嘗試一下我的數據,我會在這裏報告:P – Magikaas

+0

非常感謝!它像一個魅力!標記爲答案,我將不得不看看這個查詢如何工作,因爲這看起來很有趣:) – Magikaas