以下查询在MySQL 5.1.56中失败:
SELECT
shop_id, products.product_id AS
product_id, brand, title, price, image, image_width, image_height
FROM products, users LEFT JOIN
(
SELECT fav5.product_id AS product_id, SUM(CASE
WHEN fav5.current = 1 AND fav5.closeted = 1 THEN 1
WHEN fav5.current = 1 AND fav5.closeted = 0 THEN -1
ELSE 0
END) AS favorites_count
FROM favorites fav5
GROUP BY fav5.product_id
) AS fav6 ON products.product_id=fav6.product_id
WHERE products.product_id= 46876 AND users.user_id!=products.product_id
错误是
#1054 - Unknown column 'products.product_id' in 'on clause'
没有用户表的这种修改不会失败:
SELECT
shop_id, products.product_id AS
product_id, brand, title, price, image, image_width, image_height
FROM products LEFT JOIN
(
SELECT fav5.product_id AS product_id, SUM(CASE
WHEN fav5.current = 1 AND fav5.closeted = 1 THEN 1
WHEN fav5.current = 1 AND fav5.closeted = 0 THEN -1
ELSE 0
END) AS favorites_count
FROM favorites fav5
GROUP BY fav5.product_id
) AS fav6 ON products.product_id=fav6.product_id
WHERE products.product_id= 46876
MySQL 5.0.67中的查询都没有失败。 (我从5.0.67导出数据库并导入5.1.56,因此结构应该相同。)
products表的product_id列的类型为int(10)。 favorites表还有一个int(10)类型的product_id列。发生了什么事?
答案 0 :(得分:2)
答案 1 :(得分:1)
在5.1中,MySQL中的JOIN处理运算符优先级已更改。对于从5.0升级的人来说,这是一个常见问题 MySQL LEFT JOIN after 5.0.12 changes - How to rewrite query
答案 2 :(得分:1)
这是您的原始查询,稍微重新格式化并添加了两个括号:
SELECT shop_id, products.product_id AS
product_id, brand, title, price, image, image_width, image_height
FROM products,
( -- Parenthesis added
users LEFT JOIN
(
SELECT fav5.product_id AS product_id, SUM(CASE
WHEN fav5.current = 1 AND fav5.closeted = 1 THEN 1
WHEN fav5.current = 1 AND fav5.closeted = 0 THEN -1
ELSE 0
END) AS favorites_count
FROM favorites fav5
GROUP BY fav5.product_id
) AS fav6 ON products.product_id=fav6.product_id
) -- Parenthesis added
WHERE products.product_id= 46876 AND users.user_id!=products.product_id
括号表示SQL解析器如何解释查询,并且添加的括号内没有products
表。
将旧样式和新样式(自SQL-92以来的样式连接)混合起来是一个坏主意。
使用:
SELECT shop_id, products.product_id AS
product_id, brand, title, price, image, image_width, image_height
FROM products JOIN users ON users.user_id != products.product_id
LEFT JOIN
(SELECT fav5.product_id AS product_id,
SUM(CASE WHEN fav5.current = 1 AND fav5.closeted = 1 THEN 1
WHEN fav5.current = 1 AND fav5.closeted = 0 THEN -1
ELSE 0
END) AS favorites_count
FROM favorites fav5
GROUP BY fav5.product_id
) AS fav6 ON products.product_id=fav6.product_id
WHERE products.product_id = 46876
!=
加入速度很慢(实际上是笛卡尔积)。