我有一张包含类别信息的表。
该表有一个标记父类别和子类别的字段。
我尝试通过查询列出父类别,然后列出其子类别。
我试过像
这样的东西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'
我确信所有字段名称都是正确的。
答案 0 :(得分:1)
首先,db引擎读取列[table]。[column],而不是相反。所以它不会理解CategoryID.categories是什么 - 没有名为CategoryID的表。
您已将表格定义为
FROM categories AS parents
LEFT JOIN categories AS child
所以你需要使用你给他们的名字来引用它们。即。
SELECT
parents.CategoryId as ParentId,
child.CategoryId as ChildId,
...
答案 1 :(得分: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]。您首先使用列名称。
答案 2 :(得分:0)
在SELECT
下,您正在撰写CategoryID.categories
和CategoryName.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