2012-07-13 76 views
1

我有一個表,其中每個記錄是:ID,組ID和筆記字段。 該ID不是唯一的,它可以與多個組ID相關聯。並且每個ID-groupID組合可以與多個筆記相關聯。 我試圖在這裏打印的主要數據是筆記字段。如何從數據庫中選擇要組織的數據,如此報告

id    | groupID | notes 
------------------------------------------------------------------ 
JWOFJ903JCKDF8 | groupID-22 | new id, new id-groupID combo 
JWOFJ903JCKDF8 | groupID-33 | repeat id (line 1), new id-groupID combo 
JWOFJ903JCKDF8 | groupID-33 | repeat id (lines 1&2), repeat id-groupID (line 2) 
... 
DF8#CKJ90JJ3WO | groupID-22 | new id, new id-groupID combo 
DF8#CKJ90JJ3WO | groupID-44 | repeat id (line 4), new id-groupID combo 
... 

當打印數據,我怎麼能選擇的音符,使得相同ID,組ID組合下摔倒所有音符組合在一起?並且所有屬於相同ID的groupID被分組在一起?

所以,我的報告將是這個樣子:

JWOFJ903JCKDF8 
    -groupID-22 
     - [line 1 of the data] new id, new id-groupID combo 
    -groupID-33 
     - [line 2 of the data] repeat id (line 1), new id-groupID combo 
     - [line 3 of the data] repeat id (lines 1&2), repeat id-groupID (line 2) 
DF8#CKJ90JJ3WO 
    -groupID-22 
     - [line 4 of the data] new id, new id-groupID combo 
    -groupID-44 
     - [line 5 of the data] repeat id (line 4), new id-groupID combo 

我應該指出,這個表是非常大的 - 超過20萬次的記錄和成長。

+0

GROUP BY ID然後按groupID排序,然後您將擁有預先定義的資源,然後您可以在後端使用 – GTSouza 2012-07-13 23:07:49

回答

1

很簡單事實上:

1 /選擇所需的記錄(由ID和的groupId訂購)

SELECT id,groupID,notes 
    FROM <your table name> 
WHERE ... 
ORDER BY id, groupID 
LIMIT ... 

2 /限制的結果與一個WHERE檢索一個簡單的ID的結果和/或LIMIT(我懷疑你想在單個報告中顯示這些200k記錄)。閱讀關於你的前端爲SELECT命令

3/MySQL文檔,使用一個變量來計算結果和indentate每次更改ID或組ID

的。如果我可以建議,你的數據庫模型應該等來改變這樣的:

  • 列ID應該是唯一的,就像一個自動增加的關鍵
  • 新列(我們稱之爲鍵)應存儲電流id
  • 如果列的groupId是指現有的表組,變化這個表同樣的方式:
    • 一個獨特的自動增加的id列,名稱,
    • ,並在你的記錄表,只存儲羣組表ID作爲列名建議