2014-01-05 57 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