我有一张 table :
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
但是我得到了 16 行数据,它在 table_b 中循环并显示 table_a 中每行的 4 个值
最佳答案
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
的计算。
关于mysql - 如何将一个表与另一个只有 1 个公共(public)值的表连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55935329/