简体   繁体   中英

MySQL select query with sub-select as column

I'm currently working with the following PHP code:

$pages = $Database->query("SELECT page_id FROM pages WHERE page_parent = '0'");
$pages = $pages->fetchAll(PDO::FETCH_ASSOC);
foreach ($pages as $page_key => $page) {
    $pages[$page_key]['page_children'] = $Database->prepare("SELECT page_id FROM pages WHERE page_parent = :id");
    $pages[$page_key]['page_children']->execute(array(
        ':id' => $page['page_id']
    ));
    $pages[$page_key]['page_children'] = $pages[$page_key]['page_children']->fetchAll(PDO::FETCH_ASSOC);
}
echo '<pre>';
print_r($pages);
die();

It should be fairly obvious what it is doing, however:

  1. Select all "page" records with no parent (page_parent = 0)
  2. Select all "page" records which is a child of the parents in Step 1

Is there a way to combine this into a single SQL statement?

Updated to show desired output:

Array
(
    [0] => Array
        (
            [page_id] => 1
            [page_children] => Array
                (
                    [0] => Array
                        (
                            [page_id] => 2
                        )

                    [1] => Array
                        (
                            [page_id] => 3
                        )

                )

        )

)

You can use an INNER JOIN

  SELECT a.* 
  FROM pages a
  INNER JOIN pages b on a.page_parent = b.page_id 
  where b.parent_page ='0';

and if you want also the parent without children you can use left join

  SELECT a.* 
  FROM pages a
  LEFT JOIN pages b on a.page_parent = b.page_id and  b.parent_page ='0';

or you can use a union

  SELECT a.* 
  FROM pages a
  INNER JOIN pages b on a.page_parent = b.page_id 
  where b.parent_page ='0'
  union all
  SELECT *
  FROM pages 
  WHERE page_parent = '0'

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