我想检索具有给定父类别的所有子类别,并且我想将我的products表连接到该结果。结果应该是面包屑导航,用户可以点击父类别并使用子类别检索该类别中的所有产品。
Breadcrumb看起来像这样:Electronic >> Music >> MP3-Player >> Flash
如果用户点击“音乐”,结果应包含“音乐”“MP3播放器”和“Flash”类别中的所有产品。
我使用嵌套集,但我发现很难用复杂的查询处理它。
我的数据库看起来像这样:
category_table:ID / Name / lft / rgt products_table:ID / Title / description / pic / category_id / ...
我的查询现在看起来像这样:
$result=mysql_query('SELECT *, node.id, node.name
FROM category AS node,
category AS parent,
category AS sub_parent,
(
SELECT node.name
FROM category AS node,
category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.id = 23
GROUP BY node.name
ORDER BY node.lft
)AS sub_tree JOIN products ON products.id = id
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
AND sub_parent.name = sub_tree.name
GROUP BY node.name
ORDER BY node.lft;') or die(mysql_error());
但是这给了我错误“#1104 - SELECT会检查超过MAX_JOIN_SIZE行;检查你的WHERE并使用SET SQL_BIG_SELECTS = 1或SET MAX_JOIN_SIZE =#如果SELECT没问题”。我不明白。
答案 0 :(得分:0)
试试这个PHP脚本。它可能有几个语法错误,我还没有测试过,但它应该完全按照你想要的那样做。
需要注意的是,您需要在categories
表格中添加一个名为category_parent_id
的字段,并将其默认值设置为0
或null
。
class breadcrumbNav
{
private $dataArray = array();
private $breadcrumb = array();
public function __construct()
{
$this->getAllRecords();
return;
}
private function getAllRecords()
{
$result = $db->prepare("
SELECT p.ID as product_id, p.title AS product_title, p.description AS product_description, p.pic AS product_picture,
c.ID as category_id, c.Name as category_name, c.lft AS category_lft, c.rgt AS category_rgt, c.parent_id AS category_parent_id
FROM products p
LEFT JOIN categories c
ON p.category_id = c.ID
");
$result->execute();
$this->dataArray = $result->fetchAll(PDO::FETCH_ASSOC);
return;
}
function buildBreadcrumb($recordId, $firstRun = true)
{
foreach($this->dataArray as $row)
{
if(($row['product_id']==$recordId && $firstRun) || ($row['category_id']==$recordId && $firstRun===false))
{
$this->breadcrumb[] = '<a href="?categoryId=' . $row['category_id'] . '">' . $row['category_name'] . '</a>';
if($row['category_parent_id']!==0 && !is_null($row['category_parent_id']))
{
$this->buildBreadcrumb($this->buildBreadcrumb($row['category_parent_id'], false));
}
}
}
return implode(' >> ', $this->breadcrumb;
}
}
$currentProductId = 'ENTER THE PRODUCT ID HERE';
$breadcrumbObject = new breadcrumbNav();
$breadcrumb = $breadcrumbObject->buildBreadcrumb($currentProductId);