2017-05-06 69 views
0
MySQL查詢

有格式提高徵求意見2層層次

| ID |ID_PARENT| ... 

與意見表如果父等於0,那麼它是根評論,孩子有家長參考。

只有2級的評論層次結構。所以,家長的意見和所有答案作爲第二級。

它在目前2個查詢選擇:

  • 父母的ID(自動增量)第一

    select id, txt 
    from comments 
    where id_parent = 0 
    order by id desc limit 500 
    
  • 然後從第一個查詢所有的ID都存儲在陣列和查詢的孩子,即

    select id, txt, id_parrent 
    from comments 
    where id_parent in (58286, 55857, 54242, 53937, 53770, 52825, 51765, 51204, 50996, 50810, 44735, 43680, 43576, 42336, 41440, 41157, 39715, 38973, 38614, 36560, 36331, 36099, 35819, 35280, 33950, 33607, 33503, 32802, 30689, 27807, 27712, 26821, 25895, 23927, 23485, 23433, 22709, 22706, 22252, 21203, 20293, 20041, 19824, 19619, 19560, 19233, 17209, 17129, 16879, 16822, 16602, 14060, 13992, 13986, 13137, 13074, 12294, 10729, 10698, 10690, 10689, 10687, 10679, 10677) 
    order by id_parent desc, id asc 
    

然後從第二個查詢的結果開始迭代父節點和子節點。 有時候有500個id,它看起來很糟糕......

有沒有可能的優化?

回答

0

以下查詢應該在1次出行中獲得所有這些註釋,並按照其子女在ID前面的順序排序。

SELECT case when parent_id = 0 
THEN parent_id 
ELSE id 
END as sort_id, comments.* FROM comments ORDER BY sort_id, parent_id, id ASC 

這就是你想要做的?

如果你有機會獲得的東西都保存的方式,當它是一個頂級的評論可以改變PARENT_ID值設置爲NULL,你可以這樣做使這個查詢快了很多:

SELECT IFNULL(parent_id, id) as sort_id, comments.* 
FROM comments ORDER BY sort_id, parent_id, id ASC