0

以下查询在 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 表确实有一个 int(10) 类型的 product_id 列。收藏夹表还有一个 int(10) 类型的 product_id 列。到底是怎么回事?

4

3 回答 3

2

就像从表中交换一样简单:

FROM users, products LEFT JOIN

小心,您正在混合连接符号

于 2012-11-04T20:02:47.513 回答
1

MySQL 5.1 中的 JOIN 处理运算符优先级已更改。5.0.12 更改后从 5.0 MySQL LEFT JOIN 升级的人的常见问题 - 如何重写查询

于 2012-11-04T20:06:18.850 回答
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

!=连接会很慢(它实际上是笛卡尔积)。

于 2012-11-04T20:12:21.693 回答