2014-01-05 170 views
0

我上了3路樹工作在MySQL或父ID專門蛋糕的孩子的數量和我的表結構我怎樣才能得到1.3

+----+---------+-----------------------+ 
| id | user_id | leg_type|parent_user_id 
+----+---------+-----------------------+ 
| 1 | 1011 | M  |1000   | 
| 2 | 1012 | L  |1000   | 
| 3 | 1013 | R  |1000   | 
| 4 | 1014 | M  |1011   | 
| 5 | 1015 | R  |1011   | 
| 6 | 1016 | M  |1012   | 
+----+---------+-----------------------+ 

現在我要搜索一個特定的ID讓說parent_user_id(1000)如何可以找到M,L和R

例如1000(M)= 1011,1014,1015 {3} 1000(L)= 1012,1016 {2} 孩子的數1000(R)= 1013 {1}

Array(
    "1000"=>Array(
      "M" => 3 
      "L" => 2 
      "R" => 1 
      ) 
) 

任何優化的解決方案。我嘗試了一切,但不值得。

編輯:圖片可視化

enter image description here

+1

後取其你嘗試,你認爲是最接近的。 – Dave

回答

0

我不知道很多關於蛋糕的PHP,但如果查詢你可以試試下面的

我已測試爲你的表名

select `t1`.`parent_user_id`,`t1`.`leg_type`,count(`t1`.`leg_type`) as `leg_type_count` 
from `test` `t1` 
inner join `test` `t2` on `t2`.`leg_type` = `t1`.`leg_type` 
AND `t1`.`parent_user_id` = `t2`.`parent_user_id` 
WHERE `t2`.`parent_user_id` = 1011 
group by `t1`.`leg_type` 

在這裏,您可以檢查http://sqlfiddle.com/#!2/2e9f0/7

+0

結果不適合其他值。請嘗試http://sqlfiddle.com/#!2/77187/3/0 它應該返回 1011(R)= 1 1011(M)= 1 但結果是別的。那有意義嗎 ? –

+0

讓我檢查是什麼問題 –

+0

我的不好我很抱歉,我在之前的查詢中有一個小錯誤,我在http://sqlfiddle.com/#!2/2e9f0/18上解決了這個問題,並且還更新了我的答案。請立即檢查 –

0

試着在孩子們身上找到一個找到的地方,然後使用Set :: combine命令來得到你的結果。

$array = $this->User->find('all', array('conditions' => array(
    'User.parent_user_id' => 1000))); 

然後執行:

$array = Set::combine($array, '{n}.User.leg_type', '{n}.User.id', '{n}.User.parent_user_id'); 
+0

感謝您的回覆。我試了一下,只給一級數據,因爲我想要所有級別的數據。請參閱問題 –

+0

中的示例好吧,從一個層面來看,它自己開始變得非常昂貴。讓CakePhp爲你做好工作可能會更好。看看設置parent_id並使用$ this-> find('threaded') http://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/Models.html#find -threaded – alabount