2017-05-30 52 views
0

我有2个通常的表,产品和类别,并且由于多对多关系,我创建了一个关联两者的关键映射表。此关联表,例如就像这样:通过关联表查询产品,类别

id product_id category_id 
1  2   4 
2  2   6 
3  3   4 
etc 

,他们是外键到相应的product_idcategory_id主键。

所以现在我试图编写一个查询来测试结果。通常我想让它看到属于特定类别的一些产品。但我已经尝试了几个查询,但它告诉我,我在mysql语法中有一个错误。

select products.name 
from products 
join producto-categoria 
on producto-categoria.product_id = products.id 
join categorias 
on producto-categoria.category_id = categorias.id 
where categorias.id = 3 
limit 100 

其实我第一次创建在phpMyAdmin结构,然后上传相应的CSV文件,然后终于联系他们通过自己的FK具有关联表(也称为键映射表)创建索引,我没有创建FK链接时出现任何错误。 InnoDB作为引擎。

+2

重命名表,以便它们不会对他们有连字符。 –

回答

0

producto-categoria重命名为productocategoria。连字符导致语法错误,因为它被解释为负号。你也可以避开这个名字,但最好有一个“简单”的名字,而不是包含非标准字符的名字。

然后两两件事:

  • 使用table表的别名。
  • 摆脱加入categorias,因为表未使用。

所以:

select p.name 
from products p join 
    productocategoria pc 
    on pc.product_id = p.id 
where pc.category_id = 3 
limit 100 
+0

谢谢!我必须等待10分钟才能批准它。你的观点完全正确。连字符让我怀疑,但它并没有完全唤醒我实现。关于别名, – Arminius

+1

我会买你的书。标题非常有趣,我尽我所能使用sql来创建销售报告。肯定是我必读的。 – Arminius

相关问题