2011-03-16 77 views
0

我有以下表格:使用更簡單的方法加入

作者:

ID的用戶名郵箱密碼鹽 email_salt email_verified IP_ADDRESS

Author_threads:

thread_id,author_id

主題:

ID,標題,內容,創造

標籤:

ID,名稱

Thread_tags:

tad_id,THREAD_ID

我想選擇最新的30個線程,它們的作者和他們所有的標籤。這是我使用的SQL語句:

 SELECT thread.title, thread.id as thread_id, 
     thread.content, author.username, author.id as author_id, 
     GROUP_CONCAT(DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',') AS tags 
     FROM thread 
     JOIN thread_tags ON thread.id = thread_tags.thread_id 
     JOIN tag ON thread_tags.tag_id = tag.id 

     JOIN author_threads ON thread.id = author_threads.thread_id 
     JOIN author ON author_threads.author_id = author.id 

     GROUP BY thread.id DESC 
     LIMIT 0, 30 

有沒有更簡單的方法來做到這一點?

+0

這是MySQL嗎?您應該包含數據庫類型標記。 – JeffO 2011-03-16 15:32:09

+0

是的,很抱歉,這是MySQL – 2011-03-16 15:45:27

回答

0

我認爲GROUP BY應該是ORDER BY?

除此之外,我確信你正在做正確的原因。

由於您需要來自所有表格的值,因此您需要將它們全部加入,這就是您所做的。

+0

不,「GROUP BY」子句是正確的;他使用一個名爲'GROUP_CONCAT'的MySQL字符串聚合來將標籤連接成逗號分隔的列表,儘管SQL在'SELECT'子句中選擇非分組和非聚合列時不合法。 – 2011-03-16 15:33:58

+0

GROUP BY thread.id DESC? DESC看起來不合適... – MatBailie 2011-03-16 15:35:24

+0

這是合法的MySQL語法。 – 2011-03-16 15:48:21

0

您唯一的選擇是使用多表選擇,例如,

SELECT thread.title, thread.id as thread_id, 
    thread.content, author.username, author.id as author_id, 
    GROUP_CONCAT(DISTINCT tag.name ORDER BY tag.name DESC SEPARATOR ',') AS tags 
    FROM thread, thread_tags, tag, author_threads, author 
    WHERE thread.id = thread_tags.thread_id 
     AND thread_tags.tag_id = tag.id 
     AND thread.id = author_threads.thread_id 
     AND author_threads.author_id = author.id 
    GROUP BY thread.id DESC 
    LIMIT 0, 30 

雖然對此的支持可能依賴於數據庫。

+0

ARGH! *運行尖叫的山丘* – MatBailie 2011-03-16 15:36:30

+0

爲什麼,這是什麼問題?必須太習慣於Oracle :-) – Gnat 2011-03-16 15:37:37

+0

嗯,過度反應也許,但我個人建議不要使用這種(公認的語法正確)風格。 OP使用的風格存在,因爲它的維護性更好:) – MatBailie 2011-03-16 15:38:01