从SELECT查询中获取Max值的记录

时间:2015-01-01 15:59:45

标签: mysql sql navicat

我在查询中尝试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

我想获得价格为record的{​​{1}},其中包括:

max value

我正在使用带有MySQL服务器的Navicat

更新: 我确实尝试过使用:

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

但它没有用,因为返回的id是错误的

5 个答案:

答案 0 :(得分:1)

使用Max函数:)从...中选择MAX(列)

答案 1 :(得分:1)

执行此操作时会发生什么。

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

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 ) 

答案 2 :(得分:0)

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

答案 3 :(得分:0)

试试这个:

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

答案 4 :(得分:0)

试试这个:

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)