Select mysql 中的最小值及其整列

Select Minimum value and their entire column in mysql

考虑以下两个 table,

tab1:-

**id**   **name** 
  1     aaa
  2     bbb
  3     ccc

tab2:-

**id** **reference_id** **value**  **category**
 1               2         0.5          5
 2               2         0.03         9
 3               3         0.9          8
 4               1         0.3          3
 5               1         0.1          2

在 tab2 中,来自 tab1 (reference_id) 的 id 有 2 个值等等,我需要每个 id 的最小值,下面是我试过的代码 SELECT tab1.name,tab1.id,MIN(tab2.value) as VAL,tab2.category FROM tab1 JOIN tab2 ON tab1.id=tab2.reference_id WHERE 1 GROUP BY tab1.id 我低于输出

**name** **id** **VAL** **category**
  aaa       1     0.1       3
  bbb       2     0.03      5
  ccc       3     0.9       8

似乎最小值正确但其他列显示错误值,我需要如下输出,

**name** **id** **VAL** **category**
  aaa       1     0.1       2
  bbb       2     0.03      9
  ccc       3     0.9       8

感谢任何帮助

你应该使用一些嵌套子查询

  SELECT tab1.name
      ,tab1.id
      , t2.VAL
      ,t2.category 
  FROM tab1 
  JOIN (   select reference_id, val, category 
from tab2 
inner join (
      SELECT 
          ,tab2.reference_id 
          ,MIN(tab2.value) as VAL
      FROM  tab2
      group by tab2.reference_id 
) t on t.reference_id = tab2.reference_id and t.val = tab2.value 
) t2 on tab1.id = t2.reference_id