简体   繁体   English

MySQL选择查询,子选择作为列

[英]MySQL select query with sub-select as column

I'm currently working with the following PHP code: 我目前正在使用以下PHP代码:

$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) 选择所有没有父项的“页面”记录(page_parent = 0)
  2. Select all "page" records which is a child of the parents in Step 1 选择所有“页面”记录,这些记录是步骤1中父母的孩子

Is there a way to combine this into a single SQL statement? 有没有一种方法可以将其组合为单个SQL语句?

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 您可以使用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'

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

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