简体   繁体   English

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

[英]Get record with Max value from SELECT query

I am trying to get max value of a column in my query but I cant found any solution. 我正在尝试get max value查询中列的get max value ,但找不到任何解决方案。 My query is 我的查询是

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

Then I receive some records like the following 然后我收到一些如下记录

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

I want to get the record with the max value of price, which are: 我想获取价格max valuerecord ,这些record是:

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

I am using Navicat with MySQL server 我在MySQL服务器上使用Navicat

Update: I did try using: 更新:我确实尝试使用:

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

But it didnt work as the returned id is wrong 但是它没有用,因为返回的ID是错误的

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

What happens when you do this. 当您这样做时会发生什么。

Change all your old style comma separated join to Inner join for better readability. 将所有旧样式的逗号分隔联接更改为内部联接,以提高可读性。

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(col),但请注意,此col必须是数字而不是字符串

Try this : 尝试这个 :

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

Try this one: 试试这个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM