sql自联接,从一个表中选择类别和子类别

时间:2013-06-29 16:23:38

标签: sql join

我正在尝试在一个表中创建一个包含类别和子类别的论坛,我想在一个查询中选择所有cat和subcat但不知何故查询给我这样的错误消息

Unknown column 'fcat.fcat_id' in 'on clause'

虽然我无法弄清楚出了什么问题。以下是查询:

SELECT fcat.id          fcat_id, 
       fcat.name        fcat_name, 
       fcat.description fcat_description, 
       fcat.order       fcat_order, 
       fcat.url         fcat_url, 
       fcat.visibility  fcat_visibility, 
       fcat.parent      fcat_parent, 
       fcat.created_at  fcat_createdat, 
       fcat.is_active   fcat_isactive, 
       fsub.id          fsub_id, 
       fsub.name        fsub_name, 
       fsub.description fsub_description, 
       fsub.order       fsub_order, 
       fsub.url         fsub_url, 
       fsub.visibility  fsub_visibility, 
       fsub.parent      fsub_parent, 
       fsub.created_at  fsub_createdat, 
       fsub.is_active   fsub_isactive 
FROM   forum_categories fcat 
       LEFT OUTER JOIN forum_categories fsub 
                    ON fcat.fcat_id = fsub.fsub_parent
ORDER  BY fcat.fcat_id; 

有了这个错误,我甚至无法测试查询结果是否符合我的预期。请帮忙。 (^ __ ^')

PS:如果你能帮助我简化陈述,那对我很有帮助。提前致谢。 :)

1 个答案:

答案 0 :(得分:1)

替换

ON fcat.fcat_id = fsub.fsub_parent

ON fcat.id = fsub.fsub_parent

<强> QUERY:

SELECT fcat.id          fcat_id, 
       ...
FROM   forum_categories fcat 
       LEFT OUTER JOIN forum_categories fsub 
                    ON fcat.id = fsub.fsub_parent
ORDER  BY fcat.id;