简体   繁体   中英

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. Something like this:

Query for all parents:

SELECT * FROM parents WHERE deleted=0;

Than in PHP in foreach

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 => (
    //...
   )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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