SQL没有看到别名

时间:2018-12-27 11:52:13

标签: mysql sql database

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”

2 个答案:

答案 0 :(得分:0)

我认为您需要关联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;

答案 1 :(得分:0)

您的查询没有任何这种形式。我建议通过限定 all 列引用来编写查询:

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
                 );