【问题标题】:Join on non unique column [closed]加入非唯一列[关闭]
【发布时间】:2021-04-25 16:56:06
【问题描述】:

我在 DB 中有两个表,我想从这些表中选择并连接一些数据。

第一张桌子有一些顾客:

customer id
Dave 1
Tom 2

第二个表有一个产品列表和一个表明哪个客户购买了该产品的列:

id product isin customer id
1 PC XV452889 1
2 phone VN865232 2
3 laptop PL201325 1

我尝试了 INNER JOIN 以获得一个表格作为输出,其中列出了已购买的每种产品,谁是它的客户。

期望的输出:

id product isin customer id customer
1 PC XV452889 1 Dave
2 phone VN865232 2 Tom
3 laptop PL201325 1 Dave

我尝试了内连接,但答案是空的,就像你不能在一个非唯一列上连接两个表。已经两天了,我试图解决它。

select table2.product, table2.customer_id 
from table2 
   inner join table1 on table1.id = table2.customer_id;

Hers 是我在类似表上运行的查询(allocations 表相当于上面产品的第二个表,orders 相当于 customer 表):

【问题讨论】:

  • 问题是什么?
  • edit您的问题并添加您尝试过的查询。
  • 给定样本数据,一个内连接(例如,在 Mureinik 给出的答案中)most certainly works
  • 如果您只查看您的数据并尝试在 parer 表上手动执行 table1.id = table2.customer,您会发现没有满足此条件的行。而且你会很容易地找到正确的条件,因为没有那么多列可以蛮力。真的,看起来花在家庭作业上的时间很少。
  • 您似乎过于简化了minimal reproducible example,因此它不再重现该问题。鉴于您的屏幕截图(顺便说一句,最好将其发布为代码格式的文本),看起来 orders.idallocations.id 指的是不同的分离 id,所以也许您应该加入 orders.id = allocation.order_id 而不是 orders.id = allocations.id .

标签: sql postgresql join select


【解决方案1】:

您可以在product.customer_id 上加入customer.id

SELECT p.*, c.customer
FROM   products p
JOIN   customer c on p.customer_id = c.id

【讨论】:

    【解决方案2】:

    感谢大家对他加入的回答!!! 我在查询中发现了错误,它在 orders.instructions 之后缺少“,”... 查询太长):

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      相关资源
      最近更新 更多