2016-03-21 41 views
1

我們有兩個表,截圖附我如何使用MySQL的加入安排與最新的答覆對話

this image contains every single piece of message sent

這個表命名爲消息

this image contacts details of a every conversation started by a student to teacher

此表被命名爲對話

現在每次學生髮送消息時,會話表都會檢查c通過convo唯一ID存在反覆,然後將該消息放在數據庫上,其中sender_id作爲學生的唯一ID receiver_id作爲教師的唯一ID,convo作爲conversation_id,對於每個學生和教師對話都是唯一的。

我們想要做的是,我們要顯示像臉譜這樣的對話,最新的對話與最新的信息將在最上面,我們要找到最新的信息與created_at,當然學生只能看到對話他開始幫助我們,我們在這裏卡住了,無法爲它編寫正確的MySQL查詢,我們將使用CodeIgniter的框架用於後端

到目前爲止,我們想出了這個,但好像不工作

$this->db->select('*'); 
$this->db->from($this->conversation_table_name); 
$this->db->join($this->message_table_name,'conversation.convo = messages.convo'); 
$this->db->where('conversation.student',$student_number); 
$query = $this->db->get(); 
+1

看起來你可能只需要設置一個ord呃,使用'$ this-> db-> order_by(「created_at」,「desc」);'這會按照創建的時間排序消息,最新的優先 – gabe3886

+0

是的,你需要設置一個順序(由created_at或由id字段)在DESC順序。另外,我不確定我會使用varchar作爲我的連接字段。 – cfnerd

回答

0
$this->db->select('*'); 
$this->db->from($this->conversation_table_name); 
$this->db->join($this->message_table_name,'conversation.convo = messages.convo'); 
$this->db->where('conversation.student',$student_number); 
$this->db->group_by("conversation.sender_id"); 
$this->db->order_by("messages.created_at", "desc"); 
$query = $this->db->get(); 
+0

嗨這個解決方案工作,我可以知道怎麼會從表老師得到老師的名字?簡單的列就像teachers.teacher_name,它具有唯一的teacher_id – runningmark

+0

首先將message_id添加到消息表中。然後在where條件之前添加$ this-> db-> join($ this-> teachers_table_name,'messages.teacher_id'='teachers.teacher_id'); –