从表A到表B的SQL请求,具有随机值

时间:2020-04-07 20:11:09

标签: python sql pandas python-2.7 sqlite


我有两个这样的桌子

table_A:                                        table_B:                  

id    reference_1      reference_2          id   data_1       id data_2       
1     gh32             chocolate             1    abc          ab28
2     fg52             cacao                 2    def          cd98    
3     cd98             cofe                  3    ghi          fg52
4     ab28             milk                  4    klm          gh32

两个表包含多行和多列。

这是我的伪代码,考虑到table_B的值随机出现,并且该过程必须占用table_B的所有行。

take row 1 in table_B
search where is data_2 in table_A, reference_1
print the complete row of table_A adding data_1 of table_B

如果需要,我可以在python 2.7中编写一些动作。
谢谢您的帮助。.

1 个答案:

答案 0 :(得分:0)

如果要使用sql,则需要连接两个表,如下所示:

select a.*, b.data_1
from table_b b inner join table_a a
on b.data_2 in (a.reference_1, a.reference_2)

请参见demo
结果:

| id  | reference_1 | reference_2 | data_1 |
| --- | ----------- | ----------- | ------ |
| 1   | gh32        | chocolate   | klm    |
| 2   | fg52        | cacao       | ghi    |
| 3   | cd98        | cofe        | def    |
| 4   | ab28        | milk        | abc    |