2013-06-19 62 views
0

我正在CodeIgniter中构建一个自定义论坛,并且当前正在发布线程的最后一条消息的时间,以便对板的线程进行排序。我有一个表(父母),董事会(儿童),线程和消息(线程回复)。我想要做的就是获得当前板子中的所有线程,并在线程最后一条消息(last_msg_id)的时候对它们进行排序。如何使用MySQL Left Join按另一个表的列排序?

我以为我有查询写入正确,但是,我收到一个SQL错误。也许我的逻辑是错误的。你们有什么感想?

这是我的查询:

$query = "SELECT 
        t.child_id, t.thread_id, t.last_msg_id, 
        m.thread_id, m.message_id, m.date_posted 
        FROM forum_threads AS t 
        LEFT JOIN forum_messages ON m.message_id = t.last_msg_id AS m 
        WHERE t.child_id = " . $board_id . " 
        ORDER BY m.date_posted DESC 
        LIMIT 10"; 

这是我得到的错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS m WHERE t.child_id = 1 ORDER BY m.date_posted DESC ' at line 5 

回答

3

as m是放错了地方:

SELECT t.child_id, t.thread_id, t.last_msg_id, m.thread_id, m.message_id, m.date_posted 
FROM forum_threads AS t 
LEFT JOIN forum_messages AS m ON m.message_id = t.last_msg_id 
WHERE t.child_id = ".$board_id." 
ORDER BY m.date_posted DESC 
LIMIT 10 
+0

谢谢!有效! – ShoeLace1291