如何在MySQL中获取具有最小行值的相应id?

时间:2016-02-17 06:27:18

标签: mysql

我有两个名为dealsmp_details的表。列deal_idmp_details_id是两个主键。两个表之间存在关联,使用deal_mp_id列作为外键。我想通过deal_selling_price分组获取列名mp_details_id的所有最小记录。以下是表格:

优惠

╔═════════╦════════════╦════════════════════╗
║ deal_id ║ deal_mp_id ║ deal_selling_price ║
╠═════════╬════════════╬════════════════════╣
║    3    ║     1      ║        425         ║
║    4    ║     1      ║        540         ║  
║    5    ║     2      ║        340         ║
║    6    ║     2      ║        315         ║
║    7    ║     3      ║        425         ║
║    8    ║     3      ║        720         ║
║    9    ║     4      ║        382.5       ║
║   10    ║     4      ║        495         ║
║   11    ║     5      ║        595         ║
║   12    ║     5      ║        720         ║
╚═════════╩════════════╩════════════════════╝

mp_details

╔═══════════════╦═════════════════════╗
║ mp_details_id ║   mp_details_name   ║
╠═══════════════╬═════════════════════╣
║       1       ║ Olive Bar & Kitchen ║
║       2       ║ Thai High           ║
║       3       ║ Tonino              ║
║       4       ║ Impromptu           ║
║       5       ║ Zerruco             ║
╚═══════════════╩═════════════════════╝

我想要这样的结果:

╔═════════╦════════════╦════════════════════╗
║ deal_id ║ deal_mp_id ║ deal_selling_price ║
╠═════════╬════════════╬════════════════════╣
║    3    ║     1      ║        425         ║
║    6    ║     2      ║        315         ║
║    7    ║     3      ║        425         ║
║    9    ║     4      ║        382.5       ║
║   11    ║     5      ║        595         ║
╚═════════╩════════════╩════════════════════╝

3 个答案:

答案 0 :(得分:3)

以下查询将为您提供上述屏幕截图的结果集:

SELECT d1.deal_id, d1.deal_mp_id, d2.minPrice
FROM deals d1
INNER JOIN
(
    SELECT deal_mp_id, MIN(deal_selling_price) AS minPrice
    FROM deals
    GROUP BY deal_mp_id
) d2
    ON d1.deal_mp_id = d2.deal_mp_id AND d1.deal_selling_price = d2.minPrice

如果 想要包含mp_details表格中的信息,您可以执行以下其他加入:

SELECT d1.deal_id, d1.deal_mp_id, d2.minPrice, mp.mp_details_name
FROM deals d1
INNER JOIN
(
    SELECT deal_mp_id, MIN(deal_selling_price) AS minPrice
    FROM deals
    GROUP BY deal_mp_id
) d2
    ON d1.deal_mp_id = d2.deal_mp_id AND d1.deal_selling_price = d2.minPrice
INNER JOIN mp_details mp
    ON d1.deal_mp_id = mp.mp_details_id

请按照以下链接查看正在运行的演示:

SQLFiddle

答案 1 :(得分:0)

尝试以下查询

select 
    D.Deal_id, MD.mp_details_id, MIN(D.deal_selling_price) 
FROM
    deals D inner join  mp_details MD 
ON
    D.Deal_id = MD.mp_details_id 
GROUP BY 
   D.Deal_id, MD.mp_details_id

答案 2 :(得分:0)

使用此查询:

SELECT d.deal_id, d.deal_mp_id, d.deal_selling_price
FROM deals d
JOIN
(
  SELECT deal_mp_id, MIN(deal_selling_price) AS min_selling_price
  FROM deals
  GROUP BY deal_mp_id
) m
ON d.deal_mp_id = m.deal_mp_id AND d.deal_selling_price = m.min_selling_price