从 SELECT 查询中获取具有最大值的记录



我正在尝试在查询中get max value一列,但找不到任何解决方案。我的查询是

SELECT pz.id, 
    sz.Price + cr.AddedCost AS price
FROM piz pz, crust cr, size sz
WHERE 
    pz.SizeID = sz.id AND
    pz.CrustID = tp.id

然后我收到一些记录,如下所示

ID  price
-----------
1   95000.0
6   160000.0
10  150000.0
3   137500.0
5   122500.0
4   195000.0
2   195000.0
7   130000.0
8   205000.0
9   130000.0
11  205000.0

我想获得价格max valuerecord,它们是:

ID  price
------------
8   205000.0
11  205000.0

我正在使用 Navicat 和 MySQL 服务器

更新:我确实尝试使用:

SELECT pz.id, MAX(sz.Price + cr.AddedCost) AS price ....

但它不起作用,因为返回的 id 是错误的

当你

这样做时会发生什么。

将所有旧样式逗号分隔的连接更改为内部连接,以提高可读性。

SELECT pz.id,
       sz.Price + cr.AddedCost AS price
FROM   piz pz
       INNER JOIN crust cr
               ON pz.CrustID = cr.id
       INNER JOIN size sz
               ON pz.SizeID = sz.id
WHERE  sz.Price + cr.AddedCost = (SELECT sz.Price + cr.AddedCost AS price
                                   FROM   piz pz1
                                          INNER JOIN crust cr1
                                                  ON pz1.CrustID = cr1.id
                                          INNER JOIN size sz1
                                                  ON pz1.SizeID = sz1.id
                                   ORDER  BY price DESC limit 1 ) 

使用Max函数:)从中选择最大值(列) ...

从哪里选择 MAX(col)但请注意,此列必须是数字而不是字符串

试试这个:

SELECT pz.id, 
        sz.Price + cr.AddedCost AS price
    FROM piz pz, crust cr, size sz,
    (
    select max(sz.Price + cr.AddedCost) as v 
    from crust cr, size sz
    where pz.SizeID = sz.id
    and pz.CrustID = tp.id
    )t
    WHERE 
        pz.SizeID = sz.id AND
        pz.CrustID = tp.id AND 
        (sz.Price + cr.AddedCost) = t.v

试试这个:

SELECT pz.id, 
sz.Price + cr.AddedCost AS price
FROM piz pz, crust cr, size sz
WHERE 
pz.SizeID = sz.id AND
pz.CrustID = tp.id
HAVING
price = (SELECT max(sz.Price + cr.AddedCost) from crust cr, size sz)

相关内容

  • 没有找到相关文章

最新更新