简体   繁体   English

MySQL让所有父母都有孩子

[英]MySQL get all parents with children

I have two tables with one to many relationship. 我有两张桌子,有一对多的关系。 I need query which will return me parent with all children. 我需要查询,这将使我的父母与所有孩子一起回来。 I can do this in PHP with foreach parent give me all children. 我可以在PHP中使用foreach parent给我所有的孩子。 Something like this: 像这样的东西:

Query for all parents: 查询所有父母:

SELECT * FROM parents WHERE deleted=0;

Than in PHP in foreach 比在foreach中的PHP

SELECT * FROM children WHERE deleted=0 AND parent_id = {$parentID};

Is there a way to accomplish this with one DB query. 有没有办法通过一个数据库查询来完成此任务。 If somebody can pint me to some tutorial or some simple example :) 如果有人可以给我一些教程或一些简单的例子:)

You could do something like this : 你可以这样做:

 <?php /** a sample model **/ class Model { public function getParentsWithChildren() { $out = array(); //you have your PDO instance... $query = $pdostmt->query('SELECT * FROM parents WHERE (deleted = 0)'); while ($data = $query->fetch(PDO::FETCH_OBJ)) { $out[] = array( $data->id, $data->column_name, $this->getChildren($data->id) ); } $query->closeCursor(); return $out; } public function getChildren($parent) { $out = array(); $query = $pdostmt->prepare('SELECT * FROM children WHERE (deleted = 0) AND (parent_id = ?)'); $query->execute(array($parent)); while ($data = $query->fetch(PDO::FETCH_OBJ)) { $out[] = array( $data->id, $data->column_name, $data->other_column ); } $query->closeCursor(); return $out; } } ?> 

There you can use it like : 你可以在那里使用它:

 <?php //your php file include('path/to/the/Model.php'); $model = new Model; $parentComplete = $model->getParentsWithChildren(); ?> 

You could get an array with this structure : 你可以得到一个这种结构的数组:

(
  0 => (
         0 => 1,
         1 => example_parent,
         2 => (
                0 => (
                       0 => 1,
                       1 => example_child_1
                     ),
                1 => (
                       0 => 1,
                       1 => example_child_2
                     )
              )
       ),
   1 => (
    //...
   )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM