mysql内部连接语句错误

时间:2012-10-09 22:22:06

标签: mysql inner-join

我收到以下错误:

  

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

这是我第一次尝试加入,所以感谢您的帮助!

2 个答案:

答案 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`