如何将一个表与另一个只有1个公共值的表联接

时间:2019-05-01 11:11:19

标签: mysql sql

我有一张桌子:

ABC1234    GTR    some information    01/03/07    some information    0.55 
ABC1234    GTR    some information    14/11/18    some information    0.45 
ABC1234    GTR    some information    14/11/18    some information    0.45 
ABC1234    GTR    some information    22/11/18    some information    0.55

和另一个表格:

ABC1234   3   39448.940091 
ABC1234   3   30806.72651    
ABC1234   3   14817.730764 
ABC1234   3   13482.769

我想将第二个表末尾的4个十进制值添加到第一个表中,但是当我运行查询时:

select ta.column1, ta.column2, ta.column3, ta.column4, ta.column5, ta.column6, tb.column3  
from table_a ta,
table_b tb
where ta.column1, = tb.column1
and cd.contract_number = 'ABC1234';

我想结束:

ABC1234    GTR    some information    01/03/07    some information    0.55   39448.940091 
ABC1234    GTR    some information    14/11/18    some information    0.45   30806.72651 
ABC1234    GTR    some information    14/11/18    some information    0.45   14817.730764 
ABC1234    GTR    some information    22/11/18    some information    0.55   13482.769

但是我在循环table_b并在table_a中显示每一行的4个值的地方得到了16行数据

3 个答案:

答案 0 :(得分:0)

SQL表表示无序集。除非有列指定排序,否则不排序。

我可以推测,在第一个表中,第四列用作日期(提示:您应使用yyyy-mm-dd格式),并对行进行排序。在第二张表中,它们按第三列降序排列。

如果是这样,可以将它们合并。这在MySQL 8+中更容易表达:

select ta.column1, ta.column2, ta.column3, ta.column4, ta.column5, ta.column6, tb.column3  
from (select ta.*,
             row_number() over (partition by column1 order by column4) as seqnum
      from table_a ta
     ) ta join
     (select tb.*,
             row_number() over (partition by column1 order by column3 desc) as seqnum
      from table_b tb
     ) tb
     on ta.column1 = tb.column1 and ta.seqnum = tb.seqnum
where cd.contract_number = 'ABC1234';

您可以在早期版本中执行此操作,但是seqnum的计算最容易使用变量完成。

答案 1 :(得分:0)

尝试一下

select ta.column1, ta.column2, ta.column3, ta.column4, ta.column5, ta.column6, tb.column3  
from table_a ta inner join
table_b tb on ta.column1 = tb.column1
where cd.contract_number = 'ABC1234';

答案 2 :(得分:0)

根据当前情况列,两个表之一都具有相同的条目。如果您与此连接,则表1的第一行与表2的连接产生4行。这就是为什么您要获得16行的原因。 因此,您应该在两个表中都创建另一个列。这两种列在您的情况下都必须是唯一的。 之后,在新列的基础上加入。

我最后添加了。

table_a

ABC1234    GTR    some information    01/03/07    some information    0.55   1
ABC1234    GTR    some information    14/11/18    some information    0.45   2
ABC1234    GTR    some information    14/11/18    some information    0.45   3
ABC1234    GTR    some information    22/11/18    some information    0.55   4

table_b

ABC1234   3   39448.940091     1
ABC1234   3   30806.72651      2
ABC1234   3   14817.730764     3
ABC1234   3   13482.769        4

查询

select ta.column1, ta.column2, ta.column3, ta.column4, ta.column5, ta.column6, tb.column3 from table_a ta, table_b tb where ta.column7 = tb.column4;