如何使用MYSQL对组使用Max功能

时间:2014-11-07 08:43:10

标签: php mysql group-by max

我有3张桌子

候选信息

cdid   cdname   

1      Moussa
2      Moustafa
3      Haitham

位置

posid  posname   

1      pos1
2      pos2
3      pos3

joboffers

cdid    posid   salary
1        1       600
1        2       800
1        3       700
2        1       500
2        2       700
2        3       900
3        2       1000
3        3       500

我需要进行查询,以获得cdname每个职位的最高工资

表格应该是这样的

cdname         posname       salary

moussa          pos1          600
haitham         pos2          1000
moustafa        pos3          900

我正在使用此查询,但未获得正确的cdid

$sql="select joboffers.cdid,joboffers.posid,Max(joboffers.salary),candidates.cdname
            FROM joboffers,candidates
            Where joboffers.cdid=candidates.cdid 

            Group by joboffers.posid"; 

4 个答案:

答案 0 :(得分:0)

我认为您需要按所有非聚合列进行分组,如下所示:

SELECT j.cdid, c.cdname, j.posid, MAX(j.salary)
FROM joboffers j
JOIN candidates c ON j.cdid = c.cdid
GROUP BY j.cdid, c.cdname, j.posid

答案 1 :(得分:0)

 SELECT c.cdname, p.posname, MAX(j.salary)
 FROM joboffers j
 INNER JOIN candidates c ON j.cdid = c.cdid
 INNER JOIN positions p ON j.posid = p.posid
 GROUP BY c.cdname, p.posname

答案 2 :(得分:0)

试试这个:)

SELECT sub.cdname, sub.posname, sub.salary
FROM (
  SELECT * FROM joboffers jo
  INNER JOIN positions ps USING (posid)
  INNER JOIN candidates cd USING (cdid)
  ORDER BY posid, salary DESC
) sub
GROUP BY sub.posid

答案 3 :(得分:0)

enter code here SELECT customerNumber,MAX(金额) 来自付款 GROUP BY customerNumber ORDER BY MAX(金额);