获取osCommerce中没有sub_category或子项的父类别

时间:2012-08-07 19:58:34

标签: mysql sql oscommerce

在我的osCommerce商店中,我想获取没有子类别或子类别的类别的parent_id。

我在代码中使用了以下内容:

$categories_query = tep_db_query("select c.categories_id, cd.categories_name 
    from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd 
    where c.parent_id = '$parent_id' and 
    c.categories_id = cd.categories_id 
    order by sort_order, cd.categories_name");

当填充常量时,上述内容将转换为:

select c.categories_id, cd.categories_name 
    from categories c, categories_description cd 
    where c.parent_id = '$parent_id' and 
    c.categories_id = cd.categories_id 
    order by sort_order, cd.categories_name

2 个答案:

答案 0 :(得分:0)

你可以这样做:

SELECT c.categories_id, cd.categories_name, c.parent_id 
  FROM categories c, categories_description cd 
  WHERE c.categories_id=cd.categories_id 
  AND c.categories_id NOT IN (SELECT DISTINCT c2.parent_id FROM categories c2)
  ORDER BY c.sort_order, cd.categories_name

或者你可以这样做:

SELECT c.categories_id, cd.categories_name, c.parent_id 
  FROM categories c 
  LEFT JOIN categories_description cd 
  ON c.categories_id=cd.categories_id
  WHERE c.categories_id NOT IN (SELECT DISTINCT c2.parent_id FROM categories c2)
  ORDER BY c.sort_order, cd.categories_name

但你真正想知道的是这一行:

  c.categories_id NOT IN (SELECT DISTINCT c2.parent_id FROM categories c2)

由于parent_id列与the one you're looking up and not in another位于同一个表格中,因此您需要自行查找表格并通过其他别名引用该表格。

这部分SQL将返回被引用为父类别的所有categories_id(实际上parents_id):

SELECT DISTINCT c2.parent_id FROM categories c2

现在,当您将其放入NOT IN比较时,您将留下下面没有任何子类别的行。

答案 1 :(得分:-1)

在不知道你的桌面布局的情况下,需要一些猜测才能回答你的问题。但是,我相信你需要这样的查询:

     SELECT c.parent_id
       FROM TABLE_CATEGORIES c
  LEFT JOIN TABLE_CATEGORIES_DESCRIPTION cd ON c.categories_id = cd.categories_id
      WHERE cd.categories_id IS NULL

请注意,此LEFT JOIN ... WHERE ... IS NULL模式匹配第一个连接的表中第二个表中没有匹配项的行。