【问题标题】:SQL request from table A to table B with random values使用随机值从表 A 到表 B 的 SQL 请求
【发布时间】:2020-07-20 03:37:48
【问题描述】:


我有两张这样的桌子

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 中编写一些操作。
谢谢你的帮助。。

【问题讨论】:

  • 对不起,您的伪代码不是很清楚,也不清楚您如何存储数据以及您已经拥有什么样的代码。对我来说,它看起来也有点像家庭作业。
  • @Qohelet 我是代码的菜鸟对不起人,这也不是功课,整个代码要复杂得多,只是陷入了这种特殊情况。

标签: python sql pandas python-2.7 sqlite


【解决方案1】:

如果你想要 sql,那么你需要像这样连接 2 个表:

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    |

【讨论】:

  • 谢谢@forpas,你帮了我很多忙!还有一个问题:如果我需要使用 ('hot','cold') 向 table_B 添加另一列,例如 data_3,我说:如果 hot = 打印 table_A 的所有行但不打印牛奶
  • 如果我理解你需要一个 where 子句:where b.data_3 = 'hot' and a.reference_2 <> 'milk'。如果这不是您需要的,请将数据添加到演示中:db-fiddle.com/f/gUcJi6qhCJikZ2V18wnYBq/0 保存并发布带有您预期结果的链接。
  • 这正是我搜索的内容!但我看不到如何在您的查询中添加此参数(我更新了演示)还是只能在单独的查询中添加?
  • 没错,再次感谢! “”是缺失的链接。我必须更好地学习 SQL
猜你喜欢
  • 2022-01-19
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
  • 2022-11-18
相关资源
最近更新 更多