我收到以下错误:
1052 - 字段列表中的列'product_id'不明确
当我运行以下内容时:
SELECT `product_id`, `product_name`
FROM `products`
INNER JOIN `products_has_product_category`
ON `products.product_id` = `products_has_product_category.product_id`
AND `products_has_product_category.category_id` = 1
ORDER BY `products.product_name`
我的PRODUCTS
表有
product_id, product_name, etc
我的products_has_product_category
表有
product_id, category_id
这是我第一次尝试加入,所以感谢您的帮助!
答案 0 :(得分:1)
您需要指定product_id
来自哪个表。由于product_id
位于两个表中,因此当您SELECT
时,您需要指定要从中获取值的表。使用表别名:
SELECT p.product_id, p.product_name
FROM `products` p
INNER JOIN `products_has_product_category` pc
ON p.product_id = pc.product_id
AND pc.category_id = 1
ORDER BY p.product_name
没有表别名:
SELECT `products`.`product_id`, `products`.`product_name`
FROM `products`
INNER JOIN `products_has_product_category`
ON `products.product_id` = `products_has_product_category.product_id`
AND `products_has_product_category.category_id` = 1
ORDER BY `products.product_name`
答案 1 :(得分:0)
如果我理解你的意图,你可能意味着什么而不是AND:
SELECT `products`.`product_id`, `products`.`product_name`
FROM `products`
INNER JOIN `products_has_product_category`
ON `products.product_id` = `products_has_product_category.product_id`
WHERE `products_has_product_category.category_id` = 1
ORDER BY `products.product_name`