Minimum Value MySQL Query

2019-05-07 00:49发布

问题:

I have a data table similar to below:

ID   A   B
10  5    blue
10  8    red
10  10  yellow
20  2    black
20  17  blue
30  7    red
30  12  green
30  50  black

Basically I want to write a mySQL query to output something like:

ID   A   B
10  5    blue
20  2    black
30  7    red

It gives only unique values of 'ID' and the minimum values of 'A' of each unique 'ID'. 'B' is just the extra data that goes along with it in the row.

What should my query look like?

回答1:

You can use a subquery to identify the min(a) value for each id and then join that back to your table:

select *
from yourtable t1
inner join
(
  select min(A) A, id
  from yourtable
  group by id
) t2
  on t1.id = t2.id
  and t1.A = t2.A

See SQL Fiddle with Demo

The result is:

| ID | A |     B |
------------------
| 10 | 5 |  blue |
| 20 | 2 | black |
| 30 | 7 |   red |


回答2:

your query look like this

  SELECT *
  FROM table t1
  INNER JOIN
         (
  SELECT min(A) mi, A, ID
  FROM table
  GROUP BY ID
         ) t2
   ON t1.ID = t2.ID
   AND t1.A = t2.A


标签: mysql sql min