MySQL 1到很多。仅显示第一个表中的1个结果

时间:2011-05-03 15:15:23

标签: php mysql join pdo

示例代码

<?php
require_once('class_library/pdo.php');
$pdoConnection = new sdb('web_structure');
$select = $pdoConnection->query("SELECT main_menu.href AS main_href
    , main_menu.link_name AS main_link
    , sub_menu.href AS sub_href
    , sub_menu.link_name AS sub_link
  FROM main_menu
  LEFT JOIN sub_menu ON main_menu.id = sub_menu.main_menu_id 
  ORDER BY main_menu.position ASC");

while($row = $select->fetch())
{
    $href = $row["main_href"];
    $link_name = $row["main_link"];
    $sub_href = $row["sub_href"];
    $sub_link_name = $row["sub_link"];  

//MAIN MENU (display only once)
    echo "      <li><a href=\"$href\">$link_name</a>\n";

//SUB MENU (show all related results)
    echo "       <ul>\n";
    echo "        <li><a href=\"$sub_href\">$sub_link_name</a></li>\n";
    echo "       </ul>\n";
    echo "      </li>\n";
}
?>

输出

服务
  - 服务1

服务
  - 服务2 ...等

产品
  - 产品1

产品
  - 产品2 ......等


我想

服务
  - 服务1
  - 服务2

产品
  - 产品1
  - 产品2

2 个答案:

答案 0 :(得分:1)

<?php
require_once('class_library/pdo.php');
$pdoConnection = new sdb('web_structure');
$select = $pdoConnection->query("SELECT main_menu.href AS main_href
    , main_menu.link_name AS main_link
    , sub_menu.href AS sub_href
    , sub_menu.link_name AS sub_link
  FROM main_menu
  LEFT JOIN sub_menu ON main_menu.id = sub_menu.main_menu_id 
  ORDER BY main_menu.position ASC, main_menu.id ASC");

$p_link_name = '';
while($row = $select->fetch())
{
    $href = $row["main_href"];
    $link_name = $row["main_link"];
    $sub_href = $row["sub_href"];
    $sub_link_name = $row["sub_link"];  

//MAIN MENU (display only once)
    if ($p_link_name !== $link_name) {
        echo "      <li><a href=\"$href\">$link_name</a>\n";
    }

//SUB MENU (show all related results)
    echo "       <ul>\n";
    echo "        <li><a href=\"$sub_href\">$sub_link_name</a></li>\n";
    echo "       </ul>\n";
    if ($p_link_name !== $link_name) {
         echo "      </li>\n";
    }
    $p_link_name = $link_name;
}
?>

答案 1 :(得分:0)

你不能做这样的事吗?

$select = $pdoConnection->query("
    SELECT
        main_menu.href AS main_href,
        main_menu.link_name AS main_link
    FROM
        main_menu
    ORDER BY
        main_menu.position ASC");

while( $row = $select->fetch() ) {

    $href = $row["main_href"];
    $link_name = $row["main_link"];

    $subSelect = $pdoConnection->query("
        SELECT
            sub_menu.href AS sub_href,
            sub_menu.link_name AS sub_link
        FROM
            sub_menu
        WHERE
            main_menu_id = {$row['id']}");

    while( $subRow = $subSelect->fetch() ) {

        $sub_href = $subRow["sub_href"];
        $sub_link_name = $subRow["sub_link"];
    }

    // Output...
}