1

我正在尝试将另一个表添加到已经工作的查询中,但由于某种原因出现错误。我不确定查询是否足以继续,因为它正在由另一个函数运行,但我认为它可能只是我的查询..

这是有效的原始查询:

$listing_sql = "select " . $select_column_list . " p.products_id, p.products_model,   

p.manufacturers_id, p.products_price, p.products_tax_class_id, IF(s.status, 
s.specials_new_products_price, NULL) as specials_new_products_price, IF(s.status, 
s.specials_new_products_price, p.products_price) as final_price 

from " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS . " p 
left join " . TABLE_MANUFACTURERS . " m on p.manufacturers_id = m.manufacturers_id 
left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id,
" . TABLE_PRODUCTS_TO_CATEGORIES . " p2c

where p.products_status = '1' and p.products_id = p2c.products_id and 
pd.products_id = p2c.products_id and pd.language_id = '" . (int)$languages_id . "' and 
p2c.categories_id = '" . (int)$current_category_id . "'";

这是带有添加表和 where 子句的新查询(TABLE_PRODUCTS_ATTRIBUTES是新表 pa):

$listing_sql = "select " . $select_column_list . " p.products_id, p.products_model, 
p.manufacturers_id, p.products_price, pa.products_values_id, p.products_tax_class_id, 
IF(s.status, s.specials_new_products_price, NULL) as specials_new_products_price, 
IF(s.status, s.specials_new_products_price, p.products_price) as final_price 

from " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS . " p, " . 

TABLE_PRODUCTS_ATTRIBUTES . " pa
left join " . TABLE_MANUFACTURERS . " m on p.manufacturers_id = m.manufacturers_id 
left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id,
" . TABLE_PRODUCTS_TO_CATEGORIES . " p2c

where p.products_status = '1' and p.products_id = p2c.products_id and p.products_id = 
pa.products_id and pd.products_id = p2c.products_id and pd.language_id = '" . 
(int)$languages_id . "' and p2c.categories_id = '" . (int)$current_category_id . "'";

我的查询有什么问题吗?

4

2 回答 2

3

问题是您将逗号样式的连接语法与 JOIN 关键字混合在一起。因为它们具有不同的优先级,所以连接没有按照您期望的顺序执行(您可能期望从左到右的顺序)。

MySQL手册特别警告混合两种类型的连接:

但是,逗号运算符的优先级低于 INNER JOIN、CROSS JOIN、LEFT JOIN 等。如果在存在连接条件时将逗号连接与其他连接类型混合使用,则可能会出现“on 子句”中的“未知列”“col_name”形式的错误。

您可以为修复错误进行的一个简单更改是切换TABLE_PRODUCTS_ATTRIBUTESand的顺序TABLE_PRODUCTS

from " . TABLE_PRODUCTS_DESCRIPTION . " pd, "
. TABLE_PRODUCTS_ATTRIBUTES . " pa, "
. TABLE_PRODUCTS . " p

然而,这并不能解决真正的问题——您的查询是不可维护的。更好的是更改所有逗号样式的连接以使用JOIN关键字。这将需要从头开始重写您的整个查询,但这将使将来更容易修改。

于 2012-06-29T18:19:16.663 回答
0

尝试在查询中更改该行:

from " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_ATTRIBUTES . " pa

到:

from (" . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_ATTRIBUTES . " pa)

括号将不确定表连接的顺序是您期望的顺序。

于 2012-06-29T18:27:54.383 回答