0

在我的 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
4

2 回答 2

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的表在同一个表中,而不是在另一个表中,因此您需要自行查找表并通过另一个别名引用它。

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

SELECT DISTINCT c2.parent_id FROM categories c2

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

于 2012-08-08T05:53:45.313 回答
-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模式匹配第一个表中的行,这些行在第二个表中没有匹配项。

于 2012-08-07T20:30:34.233 回答