sql看不到别名

q0qdq0h2  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(343)
SELECT name, 
       manufacturer, 
       prize 
FROM   products AS p 
GROUP  BY manufacturer 
HAVING prize = (
    SELECT Max(prize) 
    FROM   products p1 
    WHERE  p.`id-product` = p1.`id-product` 
    GROUP  BY p1.manufacturer DESC 
    LIMIT  1
)

错误是:

1054-“where子句”中的未知列“shop.p.id.product”

3htmauhk

3htmauhk1#

你的查询没有那种形式。我建议通过限定所有列引用来编写查询:

SELECT p.name, p.manufacturer, p.prize
FROM products p
GROUP BY p.manufacturer
HAVING p.prize = (SELECT MAX(p1.prize)
                  FROM products p1
                  WHERE p.`id-product` = p1.`id-product`
                  GROUP BY p1.manufacturer DESC
                  LIMIT 1
                 );

mysql允许在 SELECT 那些不在 GROUP BY ,因此(通常)不会产生错误。但是,根据sql的规则,这是不正确的。
我不确定子查询应该做什么。如果你想要制造商提供最高的价格,那么你就不会使用 GROUP BY 在子查询中。
如果您希望为每个制造商提供价格最高的产品:

SELECT p.name, p.manufacturer, p.prize
FROM products p
HAVING p.prize = (SELECT MAX(p1.prize)
                  FROM products p1
                  WHERE p.manufacturer = p1.manufacturer
                  LIMIT 1
                 );
o2rvlv0m

o2rvlv0m2#

我想你需要帮助 subquery 取而代之的是:

SELECT p.name, p.manufacturer, p.prize
FROM products AS p
WHERE p.prize = (SELECT MAX(p1.prize) FROM products p1 WHERE p1.manufacturer = p.manufacturer);

这样,你就可以 manufacturer 这是最贵的。
编辑:如果有 product 有相同的 prize 那你就需要 PK (主/标识)列,指定唯一序列:

SELECT p.name, p.manufacturer, p.prize
FROM products AS p
WHERE p.pk = (SELECT p1.pk 
              FROM products p1 
              WHERE p1.manufacturer = p.manufacturer
              ORDER BY p1.prize DESC
              LIMIT 1
             );

如果您使用的是最新版本的 MySQL ,则还可以使用排名函数:

SELECT p.*
FROM (SELECT p.name, p.manufacturer, p.prize,
             ROW_NUMBER() OVER (PARTITION BY p.manufacturer ORDER BY p.prize DESC) AS Seq
      FROM products AS p
     ) p
WHERE Seq = 1;

相关问题