如何按适当的顺序列出父类别和子类别数据


How to list parent category and sub-category data with proper order

table : category  
    | id + category_name + parent_category_id |
    | 1  | Flower        |          0         |
    | 2  | Wall Decor    |          0         |
    | 3  | Stylish Living|          0         |
    | 4  | Mug           |          0         |
    | 5  | Sun Flower    |          1         |
    | 6  | Balsam        |          1         |

我尝试首先使用排序顺序父类别列出数据,然后列出子类别。

Flower
flower > Sun Flower
flower > Balsam
Wall Decor
Stylish Living
Mug    

当我尝试我不能像上面一样,下面是我得到的,花>太阳花和花>香脂应该在花下。

Flower
Wall Decor
Stylish Living
Mug   
flower > Sun Flower
flower > Balsam

如果有人能给出一些想法或解决方案,真的很感激。

SELECT category
FROM (
  SELECT
     IF(p.category_name is null, c.category_name, CONCAT(p.category_name, ' > ', c.category_name)) AS 'category'
  FROM category c
  LEFT JOIN category p ON c.parent_category_id = p.category_id
) s
ORDER BY category

。是我能为你想要的结果想出的最好的结果。看到它工作。

我有一个类似的结构,并使用了这个的变体:

SELECT
    p.category_id, p.category_name,
    c.category_id, c.category_name
FROM category AS c
JOIN category AS p ON (c.parent_category_id = p.category_id)    
ORDER BY p.category_name, c.category_name

你可能不得不修改你使用的那种JOIN(我知道什么应该/不应该有孩子),但它会给你所有的孩子类别和他们的父母,按照你要求的方式排序。

我终于让它准确地显示了你所追求的东西。 下面是 SQL:

SELECT p.category_name as parent_category, '' as child_category
FROM category AS p
WHERE parent_category_id not in (select category_id from category)
UNION
SELECT p.category_name as parent_category, c.category_name as child_category
FROM category AS p
JOIN category AS c ON (c.parent_category_id = p.category_id)
ORDER BY parent_category, child_category

这是输出:

+-----------------+----------------+
| parent_category | child_category |
+-----------------+----------------+
| Flower          |                | 
| Flower          | Balsam         | 
| Flower          | Sun Flower     | 
| Mug             |                | 
| Stylish Living  |                | 
| Wall Decor      |                | 
+-----------------+----------------+

请注意,这仅适用于 2 级父子关系。 如果您有第三级并且需要将其显示在三列中,那么它会变得更加复杂。

您很可能必须GROUP BY category_name和排序。

这也可能对你有很大帮助http://sqllessons.com/categories.html

这是显示具有三列 ID、名称、父 ID 的类别的列表和子列表的最佳答案

$con=mysqli_connect("localhost","root","","test");
$sql="select * from category where parent=0";
$result=mysqli_query($con,$sql);
echo "<ol>";
while($row=mysqli_fetch_array($result))
{
    echo "<li >".$row['name']."</li>";
    abc($row['id']);
}
function abc($id)
{
    global $con;
    $sql="select * from category where parent=$id";
    $result=mysqli_query($con,$sql);
    echo "<ol>";
    while($row=mysqli_fetch_array($result))
    {
        echo "<li>".$row['name']."</li>";
        abc($row['id']);
    }
    echo "</ol>";
}
echo "</ol>";

在此代码中,我们将父 ID 传递给函数和函数,然后再次调用自身以显示子类别