使用JOIN和非标准化表选择DISTINCT

时间:2012-08-16 19:50:46

标签: sql distinct

我有两张桌子

id    |    name
1     |    foo
2     |    foo
2     |    foo       <- duplicated id
3     |    bar

id    |    value
1     |    100
1     |    200
2     |    300      <- same value and id
2     |    300      <- 
3     |    500

我需要从名为foo的每个id获取第二个表中的行:

1     100
1     200
2     300
2     300

id / name表未规范化,我无法做任何事情。所以我需要从表1中选择不同的ID,从表2中选择非不同的id /值。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

您没有指定您正在使用的SQL版本。以下内容适用于任何版本:

select tabl2.*
from (select distinct id, name
      from table1
     ) join
     table2
     on table1.id = table2.id
where table1.name = 'foo'