[英]SQL query is producing an error which I can't solve
I've got the following tables which im querying: 我有以下即时查询的表格:
categories
-id
-name
-parent_id
-last
products2categories
-id
-product_id
-category_id
What im trying to do is to get the record's category name
and category id
which the product_id
in the table products2categories
is 10 and last
in the table categories
is 1 我想做的是获取记录的
category name
和category id
,表products2categories
的product_id
为10,表categories
last
为1
this is the query that i've tried to execute: 这是我尝试执行的查询:
SELECT `categories.id`,`categories.name`
FROM `categories`
JOIN `products2categories`
ON `categories.id` = `products2categories.category_id`
WHERE `categories.last` = 1
AND `products2categories.product_id`= 10
I've been returned with the following error: 我已返回以下错误:
#1054 - Unknown column 'categories.last' in 'where clause'
To demonstrate what I'm trying to get: 为了演示我想要得到的东西:
categories
-id 8
-name "my_name"
-parent_id 0
-last 1
products2categories
-id 1
-product_id 10
-category_id 1
I want to get as a result the ID of 8
and the name of "my_name" but it has to be based on the table products2categories, cause one product, can have more than one category which it's related to. 结果,我想获取ID
8
和名称“ my_name”,但它必须基于表products2categories,导致一种产品可以具有与其相关的多个类别。
Thanks in advance! 提前致谢!
Replace 更换
WHERE `categories.last` = 1
with 与
WHERE `categories`.`last` = 1
Backticks for escaping column and table names can't be used to escape the combination of table and column. 转义列和表名的反引号不能用于转义表和列的组合。 It must be applyed on both.
它必须同时应用于两者。
A quick check of your syntax: categories.last
shouldn't be categories
. 快速检查语法:
categories.last
不应该是categories
。 last
instead? last
呢?
Do as same for all other "fields" 对所有其他“字段”执行相同的操作
Use the backticks around a single identifier: 在单个标识符周围使用反引号:
So 所以
`categories.last`
should be 应该
`categories`.`last`
because the table name and the column name are separate identifiers. 因为表名和列名是单独的标识符。
In this case, you don't need the backticks at all, by the way, so it should work fine if you remove them, like this: 在这种情况下,顺便说一下,您根本不需要反引号,因此如果删除它们,它应该可以正常工作,如下所示:
categories.last
You need the backticks only for column names containing spaces or some other special characters, and maybe for names that are equal to some reserved words in some circumstances. 仅在包含空格或其他特殊字符的列名中使用反引号,在某些情况下可能需要使用等于某些保留字的名称。 But as far as I can tell, you don't need them at all in your case, and I don't recall every having had to use them.
但是据我所知,您根本不需要它们,而且我不记得每个人都必须使用它们。
You are delimiting fields incorrectly. 您不正确地分隔字段。 Delimit the table name and column name separately:
分别分隔表名和列名:
SELECT `categories`.`id`,`categories`.`name`
FROM `categories`
JOIN `products2categories`
ON `categories`.`id` = `products2categories`.`category_id`
WHERE `categories`.`last` = 1
AND `products2categories`.`product_id`= 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.