我写了一个查询并收到错误:
字段列表中的列'product_id'不明确 错误号码:1052
我需要从2个表中选择相同的ID并按价格比较这里是我写的查询:
$product_sql_test1 = $this->db->query("SELECT `product_id` and 'price' FROM `" . DB_PREFIX . "product_to_category`INNER JOIN (oc_product)ON oc_product.product_id=prdoduct_to_category.product_id WHERE product_to_category.id=product.id and price >150 and `category_id`='".$product_info['related_kv4nt_id_1']."' GROUP BY `product_id` ORDER BY rand() LIMIT 0,10");
哪里可能是错误以及如何解决?对不起,如果问题太简单了。
答案 0 :(得分:2)
在选择product_id时你必须提到表名,因为很多表都有这个列而且mysql很困惑,无法选择表中的列
$product_sql_test1 = $this->db->query("SELECT oc_product.`product_id` and 'price'
FROM `" . DB_PREFIX . "product_to_category`INNER JOIN (oc_product)ON
oc_product.product_id=prdoduct_to_category.product_id WHERE product_to_category.id=product.id and price >150 and prdoduct_to_category.`category_id`='".$product_info['related_kv4nt_id_1']."'
GROUP BY oc_product.`product_id` ORDER BY rand() LIMIT 0,10");
答案 1 :(得分:0)
使用全名:
Tablename.ColumnName
例如,在GROUP BY部分中,您不清楚您的product_id
是什么意思。
答案 2 :(得分:0)
为表和列使用别名。
像oc.product_id
(列)和oc_product oc
(表格)
答案 3 :(得分:0)
您的Select
和Group By
都需要use your alias table names along with your column names
,因为多个表中存在相同的列,因此对于哪一个用于结果会产生混淆
答案 4 :(得分:0)
正确的方法是
$product_sql_test1 = $this->db->query("SELECT `p`.`product_id`, `p`.`price` FROM `" . DB_PREFIX . "product_to_category` `p2c` LEFT JOIN `" . DB_PREFIX . "product` `p` ON `p`.`product_id` = `p2c`.`product_id` WHERE `p`.`price` > 150 and `p2c`.`category_id`='" . (int) $product_info['related_kv4nt_id_1'] . "' GROUP BY `p`.`product_id` ORDER BY rand() LIMIT 0,10");
您还应该考虑格式化SQL以使其更易于阅读