带有min和max的sql语句

时间:2012-08-19 14:07:10

标签: mysql sql database

我需要一起使用min和max来写一个声明。

SELECT companyname  FROM companies JOIN stocklist 
USING (companyid) where price =some(
( select max(price) from stocklist) , ( select min(price) from stocklist) ) ;

我需要获得最低和最高价值的公司名称,但这不起作用(因为最后一行)出了什么问题,我应该怎么做?

更新:

select companyname from stockList join companies using (companyid) WHERE price IN (select min(price) from stocklist) ;

这对我有用但只获得一个操作数,我怎么能得到两个呢?

2 个答案:

答案 0 :(得分:1)

我不喜欢在IN子句中有两个子查询的想法。这是联接明确的另一种方式:

SELECT companyname 
FROM companies c JOIN
     stocklist s
     c.companyid = s.companyid join
     (select min(price) as minprice, max(price) as maxprice
      from stocklist
     ) sm
     on s.price = minprice or s.price = maxprice

答案 1 :(得分:0)

试试这个:

SELECT companyname  FROM companies c
INNER JOIN stocklist s
ON c.companyid = s.companyid
WHERE price IN
((SELECT MAX(price) FROM stocklist ), 
 (SELECT MIN(price) FROM stocklist ))

SEE THIS FIDDLE