简体   繁体   English

用户“类别”表作为“子类别”的标题

[英]User “Categories” table as heading for “SubCategories”

I don't know if this is possible at all... But I need to create an sql query that lists all my Categories with their Sub Categories. 我根本不知道这是不可能的...但是我需要创建一个SQL查询,列出所有我的类别及其子类别。 Problem is that Categories and Sub Categories are stored in separate tables. 问题是类别和子类别存储在单独的表中。

The database structure is as follows: TABLE NAME: "Categories", COLUMNS: "ID, Name" 数据库结构如下:表名:“类别”,列:“ ID,名称”

TABLE NAME: "Sub_Categories". 表名称:“ Sub_Categories”。 COLUMNS: "ID, Name, Category_ID". 栏:“ ID,名称,类别ID”。 The category_ID is used to link each sub category to it's parent category using ID's. category_ID用于使用ID将每个子类别链接到其父类别。

Right now I just have an sql query code that pulls all the "Categories"... how can I make it so that it will show a list of sub categories under each one? 现在,我只有一个可以查询所有“类别”的sql查询代码...我怎样才能使它显示出每个类别下的子类别列表?

<?php
$catlist= mysql_query('SELECT * FROM categories WHERE hide = 0 ORDER BY `order` ASC')
or die(mysql_error());  
?>
<?php foreach ($catlist as $catitem): ?>
<h2 class="category"><?php echo $catitem['name']; ?></h2>
<?php endforeach; ?>
<?php ?>

this will get you the rest of the info - you will then need to do layout and suppress the repeating category text. 这将为您提供其余的信息-然后您需要进行布局并隐藏重复的类别文本。

SELECT * 
FROM categories c, sub_categories s
WHERE c.hide = 0 
AND s.category_id = c.category_id
ORDER BY `order` ASC

You could use a join onto the subcategories table. 您可以在子类别表上使用联接。 http://dev.mysql.com/doc/refman/5.0/en/join.html http://dev.mysql.com/doc/refman/5.0/en/join.html

However, I recommend not differentiating between top level and sub-level categories at the table level, but rather put them all in one table with the following fields: parent_id, left_id, and right_id. 但是,我建议不要在表级别上区分顶级类别和子级别类别,而应将它们全部放在具有以下字段的表中:parent_id,left_id和right_id。 Basically, this allows an unlimited depth of categories within a hierarchy. 基本上,这允许层次结构中类别的无限深度。 It may take a little research into how to properly implement it, but it is more powerful by far. 可能需要对如何正确实施进行一些研究,但是到目前为止,它的功能更为强大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM