如何获取所有相同的值字段,如类别及其子类别?

How to fetch all same value field like categories and its subcategories?

我实际上遇到了 sql 查询执行问题,我无法按我的意愿执行。

简要说明我想要什么: 这是我的 table 结构-

| id | categoryname | nameofthing | 
| 1  |   category1  |    name 1   |
| 2  |   category2  |    name 2   |
| 3  |   category 3 |    name 3   |
| 4  |   category 1 |    name 4   |
| 5  |   category 1 |    name 5   |
| 6  |   category 3 |    name 6   |

我想要显示的结果是这样的:

Category1 
 - Name 1
 - Name 4
 - Name 5
Category2
 - Name 2
Catergot3
 - Name 3

等等..

我想运行一个查询,首先获取所有相同值的类别名称,然后是它的值(nafeofthing),然后再获取下一个相同值的类别名称及其值。

请帮我实现这个!

$query=mysql_query("SELECT * FROM thing WHERE tol_id='$bid' ORDER BY categoryname, name"); 
    if(mysql_num_rows($query) > 0){
    while($row=mysql_fetch_array($query)) {
    $categoryname = $row['categoryname'];
    $name = $row['name'];
    echo"
    <div class='stuff'>
    <p>".$categoryname."</p>
        <div id='rowstuff'>
            <div id='name'>".$tname."</div>
    </div>
    </div>
    ";
}

这最好在应用层完成,但您可以通过查询获得此结果:

select coalesce(concat('- ', nameofthing), categoryname)
from ((select categoryname, null as nameofthing
       from thing t
      ) union all
      (select categoryname, nameofthing
       from thing t
      )
     ) t
order by categoryname, (nameofthing = null) desc;
       <?php
        //use GROUP_CONCAT to CONCAT all name by comma(,) group by categoryname. 'thing' is your table name
        $query = "SELECT categoryname, GROUP_CONCAT(nameofthing) as 'name' FROM thing group by categoryname ORDER BY categoryname";

        $output ='';
    $query= mysqli_query($conn, $query); 
        if(mysqli_num_rows($query) > 0){
        while($row=mysqli_fetch_array($query)) {
        $categoryname = $row['categoryname'];
        $output.="<p>".$categoryname."</p>";

        //using explode split the name in array
        $name = explode(',', $row['name']);

        $output.="<div id='rowstuff'>";

        //iterate the name from array
        for($i=0;$i<count($name);$i++){
             $output.= "<div id='name'>".$name[$i]."</div>";
        }
         $output.= "</div>";
    }
}

    echo $output;

OutPut 会像

https://www.screencast.com/t/ZWG7bqy0

$query=mysql_query("SELECT * FROM thing WHERE tol_id='$bid' ORDER BY categoryname, name"); 
$categories = [];
if(mysql_num_rows($query) > 0){
    while($row=mysql_fetch_array($query)) {
        $categories[$row['categoryname']][] = $row['name'];
    }
}
if(!empty($categories)) {
    foreach($categories as $categoryName => $subCategories) {
        echo "<div class='stuff'>
                <p>".$categoryName."</p>
                <div id='rowstuff'>";
                if(!empty($subCategories)) {
                    foreach($subCategories as $subCategory) {
                        echo "<div id='name'>".$subCategory."</div>";
                    }
                }
        echo "</div></div>";
    }
}