1

我有一个包含类别信息的表格。

该表有一个字段来标记父类别和子类别。

我试图通过查询列出父类别,然后列出其子类别。

我尝试了类似的东西

SELECT 
  CategoryID.categories as ParentID,
  CategoryName.categories AS ParentName, 
  parents.* 
FROM 
  categories AS parents LEFT JOIN categories AS child 
    ON child.Parent = parents.ParentID

但不幸的是,它对我不起作用。它给了我一个奇怪的错误。

[SQL] SELECT CategoryID.categories as ParentID, CategoryName.categories 
AS ParentName, parents.* FROM categories as parents LEFT JOIN categories as child on child.Parent = parents.ParentID

[Err] 1054 - Unknown column 'CategoryID.categories' in 'field list'

我确信所有字段名称都是正确的。

4

3 回答 3

1

首先,数据库引擎读取列 [table].[column],而不是相反。所以它不会理解 CategoryID.categories 是什么 - 没有名为 CategoryID 的表。

你这样定义你的表

     FROM categories AS parents 
LEFT JOIN categories AS child 

所以你需要使用你给他们的名字来引用他们。IE

SELECT
      parents.CategoryId as ParentId,
      child.CategoryId as ChildId,
      ...
于 2012-09-29T23:25:11.750 回答
0

尝试

SELECT
  parents.CategoryId AS ParentId,
  parents.CategoryName AS ParentName,
  parents.* -- < this is probably child.*
FROM
   categories AS child LEFT JOIN categories AS parents
     ON child.parent = parents.CategoryId

SQL 的命名约定是 [table].[column]。您首先使用的是列名。

于 2012-09-29T23:06:32.717 回答
0

SELECT你下面写CategoryID.categoriesCategoryName.categories...规则是写成alias name.field name

因此你得到错误Unknown column 'CategoryID.categories' in 'field list'

我建议你试试这样 -

SELECT parent.CategoryID as ParentCategory, parent.CategoryName as ParentCatName,
     child.CategoryID as ChdCategory, child.CategoryName as ChdCatName
FROM categories AS parents LEFT JOIN categories AS child 
     ON child.Parent = parents.ParentID

你也可以在这里查找:mysql joins with alias

于 2012-09-29T23:36:33.053 回答