MySQL选择查询,子选择为列

时间:2017-08-04 09:24:33

标签: php mysql

我目前正在使用以下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();

然而,它应该是相当明显的做法:

  1. 选择没有父级的所有“页面”记录(page_parent = 0)
  2. 选择所有“页面”记录,这些记录是步骤1中父项的子项
  3. 有没有办法将它组合成一个SQL语句?

    更新以显示所需的输出:

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

1 个答案:

答案 0 :(得分:0)

您可以使用INNER JOIN

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

如果您还想要没有孩子的父母,您可以使用左连接

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

或者您可以使用联合

  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'