选择min(ID),每个数字都有多个ID的数字,并显示其他表中相同(最小)ID的数据

时间:2016-02-26 16:27:17

标签: sql oracle

我有2个表,每个数字都包含公共ID。 table1只包含1行,每行包含一个ID。基于这个数字和相应的ID,我想在table2找到最小ID,并为每个数字(第一个表)显示这个唯一的ID。 table2包含多个ID(对于table1的数量)。

根据MT0的建议,工作的SQL是:

SELECT MIN( t2.ID ) AS min_id,
   t1.number 
FROM   table1 t1
   INNER JOIN
   table2 t1
   ON ( t2.ID = t1.ID )
WHERE  t1.number in (<list of comma separated numbers>)
GROUP BY t1.number;

现在,我还想从table3中获取(选择)相关数据(文本),其中t3.ID = t1.ID = MIN(t2.ID)。

当我尝试这样做时:

SELECT MIN( t2.ID ) AS min_id, t3.data, t1.number 
FROM  table1 t1
    INNER JOIN
    table2 t1
    ON ( t2.ID = t1.ID )
    LEFT JOIN
    table3 t3
    on ( t3.ID = t1.ID )
WHERE  t1.number in (<list of comma separated numbers>)
GROUP BY t1.number;

我得到错误&#34;不是GROUP BY表达式&#34;对于t3.data。 我在做什么(思考)错了?

谢谢。

1 个答案:

答案 0 :(得分:0)

你的逻辑难以理解。根据文本(不是示例代码),我假设t1t2之间的联接键是number,而不是id

一种方法在子查询中使用聚合:

SELECT t1.number, t3.*
FROM table1 t1 INNER JOIN
     (SELECT t2.number, MIN(t2.id) as minid
      FROM table2 t2
      GROUP BY t2.number
     ) t2
     ON t2.number = t1.ID INNER JOIN
     t3
     ON t3.t2id = t2.minid
WHERE t1.number in (<list of comma separated numbers>);

实际上,正如措辞一样,t1不是必需的:

SELECT t2.number, t3.*
FROM (SELECT t2.number, MIN(t2.id) as minid
      FROM table2 t2
      WHERE t2.number in (<list of comma separated numbers>)
      GROUP BY t2.number
     ) t2
     t3
     ON t3.t2id = t2.minid;