我有兩個表(條目和標籤)與許多一對多連接表。現在,我正在進行查詢以檢索符合條件的所有條目,併爲每個條目查詢以檢索標籤。多層MySQL查詢?
會不會有一種方式說,已經通過新的列返回的代碼,如第一次查詢的陣列?
我有兩個表(條目和標籤)與許多一對多連接表。現在,我正在進行查詢以檢索符合條件的所有條目,併爲每個條目查詢以檢索標籤。多層MySQL查詢?
會不會有一種方式說,已經通過新的列返回的代碼,如第一次查詢的陣列?
這個查詢:
SELECT e.id entry_id
, GROUP_CONCAT(t.txt ORDER BY t.txt) tags
FROM entry e
LEFT JOIN entry_tag et
ON e.id = et.entry_id
LEFT JOIN tag t
ON et.tag_id = t.id
GROUP BY e.id
將返回標籤作爲一個逗號分隔的列表。您可以在GROUP_CONCAT讀了更多的選擇:http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_group-concat
在你的應用程序,你應該能夠擴展到一個數組這很容易。例如,在PHP中,你可以使用explode
:http://php.net/manual/en/function.explode.php
如果你需要從tag
或entry_tag
表的詳細屬性,你可以添加又更GROUP_CONCAT
列,或者想爲您的數據(如JSON)的一些序列化格式和在使用GROUP_CONCAT
,或者你可以簡單地每個條目返回多行和處理結果在應用程序中的條目保持標籤一起:
$sql = '
SELECT e.id entry_id
, t.id tag_id
, t.txt tag_text
, t.published tag_published
FROM entry e
LEFT JOIN entry_tag et
ON e.id = et.entry_id
LEFT JOIN tag t
ON et.tag_id = t.id
ORDER BY e.id
';
$result = mysql_query($ql);
$entry_id = NULL;
$entry_rows = NULL;
while ($row = mysql_fetch_assoc($result)) {
if ($entry_id != $row['entry_id']) {
if (isset($entry_id)) { //ok, found new entry
process_entry($entry_rows); //process the rows collected so far
}
$entry_id = $row['entry_id'];
$entry_rows = array();
}
$entry_rows[] = $row; //store row for his entry for later processing
}
if (isset($entry_id)){ //process the batch of rows for the last entry
process_entry($entry_rows);
}
您可以使用GROUP BY
和GROUP_CONCAT
函數一次獲取所有標記爲串聯字符串。 http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
注意,GROUP_CONCAT有你有'SET group_concat_max_len = 2048的限制; '在開始時確保GROUP_CONCAT適應衆多領域。 – Pentium10 2010-02-21 20:45:46
@ Pentium10:這是一種方法。另一種方式是在你的my.cnf中指定它。儘管2048的大小看起來是任意的。就我個人而言,如果你想真正確定,我建議將它設置爲@@ max_allowed_packet。 – 2010-02-21 20:50:02
我們有很多標籤,而這個2048工作得很好。感謝分享這個變量。 – Pentium10 2010-02-21 20:54:21