2013-06-19 100 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