慕神8447489
你可以这样做。测试数据:create table tbl_cat (id int, cat_name varchar(32));insert into tbl_cat(id, cat_name) values(1, "category1"), (2, "category2");create table tbl_subcat (id int, cat_id int, subcat_name varchar(32));insert into tbl_subcat(id, cat_id, subcat_name) values(1, 1, "subcat11"), (2, 1, "subcat12"), (3, 1, "subcat13"), (4, 2, "subcat21");然后,PHP 脚本可以这样写:<?php $servername = "localhost";$username = "your_user";$password = "your_password";$dbname = "test";// Create connection$conn = new mysqli($servername, $username, $password, $dbname);// Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}$sql = "SELECT cat_name, subcat_name FROM tbl_cat LEFT JOIN tbl_subcat ON tbl_cat.id = tbl_subcat.cat_id;";$result = $conn->query($sql);$last_category = "";if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $cat_name = $row["cat_name"]; if ($cat_name != $last_category) { echo "Category: " . $cat_name .PHP_EOL; $last_category = $cat_name; } echo "\tSubcategory: " . $row["subcat_name"] .PHP_EOL; }} else { echo "0 results";}$conn->close();?>