Error: Not unique table/alias: 'companies' Database (error): 1066

Error: Not unique table/alias: 'companies' Database (error): 1066

我正在制作一个电子商务网站,我有一个管理面板来控制网站。

从管理面板激活类别和产品过滤器时,此 sql 查询:

SELECT COUNT(DISTINCT products.product_id) AS products,
       companies.company AS range_name,
       UPPER(SUBSTRING(companies.company, 1, 1)) AS `index`,
       companies.company_id AS range_id,
       'S' AS field_type
FROM products
LEFT JOIN companies ON companies.company_id = products.company_id
INNER JOIN products_categories ON products_categories.product_id = products.product_id
LEFT JOIN categories ON categories.category_id = products_categories.category_id
LEFT JOIN companies AS companies ON companies.company_id = products.company_id
WHERE products.status IN ('A')
  AND products_categories.category_id IN (261)
  AND (categories.usergroup_ids = ''
       OR FIND_IN_SET(0, categories.usergroup_ids)
       OR FIND_IN_SET(1, categories.usergroup_ids))
  AND (products.usergroup_ids = ''
       OR FIND_IN_SET(0, products.usergroup_ids)
       OR FIND_IN_SET(1, products.usergroup_ids))
  AND categories.status IN ('A',
                            'H')
  AND products.status IN ('A')
  AND (companies.status = 'A')
GROUP BY products.company_id
ORDER BY companies.company

出现故障并显示错误:

Not unique table/alias: 'companies' Database (error): 1066

谁能帮忙找出这个查询中的错误?

提前致谢:)

您将加入 companies table 两次。这很好,但你必须为它们起不同的别名。

第一个连接没有别名所以被称为相同的; 公司。第二个是别名,但再次使用相同的名称 companies,这会导致冲突。

尝试使用不同名称作为别名的好习惯,例如 companies1companies2(或者更好,任何其他更多有意义的名称),当然还要相应地更新 select 中的所有 table 引用、连接、位置、分组和顺序。