【问题标题】:sql join on joinsql 加入时加入
【发布时间】:2021-03-05 15:35:30
【问题描述】:

事务表(1 行 --> 1 个事务)

customer_code amount
A0BEFG        100
DEC21A        80

支付表(1 行 --> 1 笔交易)

customer_id   payment_type
1             cash
2             credit_card

客户表(1 行 --> 1 个客户代码)

customer_code    customer_id
A0BEFG           2
DEC21A           1

预期输出: 组合表

customer_code customer_id amount payment_type
AOBEFG        2           100    credit_card
DEC21A        1           80     cash       

也就是说,我的想法是把payment_type放到transactions表中,但是因为没有匹配变量,所以我需要先合并payment表和customer表,然后再连接到transactions表。

我试过的代码:

  with 
        connection as (
        select c.customer_code, c.customer_id, p. payment_type
        from data.payment p
        left join data.customer c on p.customer_id = c.customer_id 
    ),
        transactions as (
        select t.merchant_code, t.amount
        from data.transactions t
        )
    select 
        t.merchant_code, c.customer_id, c.amount, p.payment_type 
    from transactions as t

代码用于 PostgreSQL。

【问题讨论】:

  • merchant_code 应该被 customer_code 覆盖。但这并没有达到目标
  • customer_code 和 customer_id from customer 表是到其他 2 个表的链接。有什么问题?
  • 我无法直接合并支付表和交易表,因为 customer_code 不等于 customer_id。

标签: sql postgresql join


【解决方案1】:
SELECT c.customer_code, c.customer_id, t.amount, p.payment_type
FROM customer AS c
INNER JOIN payment AS p ON p.customer_id = c.customer_id
INNER JOIN transactions AS t ON t.customer_code = c.customer_code

【讨论】:

  • 感谢您的回答,但@forpas 回复得稍微快了一点 :)
  • @Luc 最重要的是我们帮助了你 ;)
【解决方案2】:

像这样将customer 加入其他表:

SELECT c.customer_code, c.customer_id, t.amount, p.payment_type
FROM transactions t
INNER JOIN customer c ON t.customer_code = c.customer_code
INNER JOIN payment p ON p.customer_id = c.customer_id

请参阅demo
结果:

customer_code customer_id amount payment_type
A0BEFG 2 100 credit_card
DEC21A 1 80 cash

【讨论】:

  • 我应该更好地使用内连接和内连接,还是左连接和右连接?
  • @Luc 仅当任何表可能不包含您想要的相应行并且它还取决于哪个表将是 LEFT 表的情况下,您才应该使用 LEFT join(s)你将从那里开始加入
  • 我编辑了代码以从 transactions 开始连接。如果您发现由于其他表中没有对应的行而没有获得事务,则可以将联接更改为 LEFT 联接。
猜你喜欢
  • 2014-07-15
  • 2020-03-09
  • 2014-12-18
  • 2015-03-06
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多