如何连接两个表显示其他表的max()

时间:2013-09-12 03:01:55

标签: mysql sql

我有桌子水果:

|ID|FruitName|
|1 |Banana   |
|2 |Orange   |
|3 |Apple    |

我还有表Sales:

|ID|Month|Sold|
|1 |Jan  |20  |
|1 |Feb  |10  |
|1 |Mar  |30  |
|2 |Apr  |15  |
|2 |Jan  |25  |
|3 |Jul  |25  |
|3 |Jun  |18  |

现在我想显示这个

1|Banana|Mar|30|
2|Orange|Jan|25|
3|Apple |Jul|25|

5 个答案:

答案 0 :(得分:1)

您需要将fruit表加入sales一次以获取月份,然后再次加入sales表格以获取maxSold计数,您可以使用该计数过滤掉sold计数不等于maxSold的不需要的记录。

SELECT  f.id, f.name, s.month, maxSold
FROM fruit f LEFT JOIN sales s ON f.id = s.id 
      LEFT OUTER JOIN 
        (SELECT id,  max(sold) maxSold FROM sales 
             GROUP BY id) salesMax ON salesMax.id = f.id
WHERE s.sold = maxSold

请参阅demo

答案 1 :(得分:0)

试试这个:

SELECT f.id
    ,f.fruitname
    ,s.month
    ,s.sold

FROM fruits f
LEFT JOIN (SELECT a.*
    FROM Sales a LEFT JOIN Sales b ON a.Id = b.IdAND a.Sold < b.sold
    WHERE b.Sold IS NULL) AS s 
ON s.id = f.id

销售表之间的左内联接获取最大值,然后外左联接只是添加水果名称。

答案 2 :(得分:0)

试试这个:

select a.id, a.month, a.sold, c.fruitName
from   sales a,
       (
         select month, max(sold) sold
         from   sales
         group by month
       ) b,
       fruits c
where  a.month = b.month AND a.sold = b.sold AND a.id = c.id

答案 3 :(得分:-1)

你可能不需要这个区别但是这应该对MySQL有点接近。

SELECT DISTINCT
    F.ID
    , F.FruitName
    , M.Month
    , MAX(M.Sold) AS Sold
FROM 
    Fruits F
JOIN
    Sales S ON
    F.ID = S.ID
GROUP BY F.ID, F.FruitName, M.Month, M.Sold

答案 4 :(得分:-1)

我可以在我的SQL语句中这样做。

SELECT
 fruits.ID,
 fruits.FruitName,
 Sales.Month,
 MAX(Sales.Sold) as MAX
FROM
 fruits
LEFT JOIN Sales
 ON fruits.ID = Sales.id
GROUP BY 
fruits.id