在同一个表中使用条件连接查询

发布于 2024-11-09 14:18:36 字数 165 浏览 7 评论 0原文

我已在同一个表中插入类别和子类别。

id , name , mainCat ,

这是类别的名称。如果用户添加子类别,那么我会将父类别添加到 maincat 并将子类别添加到名称中。

但当进行排序时,我会按类别进行排序。

任何人都可以建议我最好的查询吗

I have inserted both category and sub-category in same table.

id , name , mainCat ,

Here is the name of the category .If a user add a subcategory then i will add the parent category to maincat and sub category to the name.

but when come sorting i have sort Category wise.

can any one suggest me best query

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

江南烟雨〆相思醉 2024-11-16 14:18:36

只要您只有两级类别,那么使用自连接进行如下所示的查询就足够了。但是,如果您有很多级别(即层次结构),那么问题就会变得更加困难。请参阅http://mikehillyer.com/articles/managing-hierarchical-data-in -mysql/ 了解更多信息。

SELECT p.Name, s.Name
FROM Categories s
LEFT JOIN Categories p ON s.mainCat = p.ID
ORDER BY p.Name, s.Name;

As long as you only have two levels of categories then a query like the following using a self-join will suffice. However, if you have many levels (i.e. a hierarchy) then the problem becomes a lot harder. See http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ for more information.

SELECT p.Name, s.Name
FROM Categories s
LEFT JOIN Categories p ON s.mainCat = p.ID
ORDER BY p.Name, s.Name;
归属感 2024-11-16 14:18:36

我尝试了很多查询,但最后我用 php 做到了

$category = mysql_query("SELECT * FROM category WHERE mainCat = '' ORDER BY `name` ASC");

while($data = mysql_fetch_array($category)){
    $array[] = $data;
    $subCategory = mysql_query("SELECT * FROM category WHERE mainCat ='".$data['name']."' ORDER BY `name` ASC");
    echo "SELECT * FROM category WHERE mainCat ='".$data['name']."' ORDER BY `name` ASC".'<br/>';
    while($data2 = mysql_fetch_array($subCategory)){
        if($data2['mainCat']!=""){
            $array[] = $data2;
        }
    }   
}

i tried with query a lot but finally i made it with php

$category = mysql_query("SELECT * FROM category WHERE mainCat = '' ORDER BY `name` ASC");

while($data = mysql_fetch_array($category)){
    $array[] = $data;
    $subCategory = mysql_query("SELECT * FROM category WHERE mainCat ='".$data['name']."' ORDER BY `name` ASC");
    echo "SELECT * FROM category WHERE mainCat ='".$data['name']."' ORDER BY `name` ASC".'<br/>';
    while($data2 = mysql_fetch_array($subCategory)){
        if($data2['mainCat']!=""){
            $array[] = $data2;
        }
    }   
}
黯然#的苍凉 2024-11-16 14:18:36

你试试下面吗:

SELECT t1.id, t1.name
FROM tablename t1
LEFT JOIN tableName t2
ON t2.name = t1.mainCat

have u try below:

SELECT t1.id, t1.name
FROM tablename t1
LEFT JOIN tableName t2
ON t2.name = t1.mainCat
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文