与和一起奋斗

时间:2018-11-16 11:26:52

标签: sql

我正在尝试通过连接表来获取产品的帐号。

https://www.db-fiddle.com/f/q6GJFqFqrNrDgMd3fnmEwG/3

我的帐户表的结构如下:

| account_no | line_number | content |
| ---------- | ----------- | ------- |
| CQ01       | 5           | CUST1   |
| CQ01       | 6           | Q       |
| CQ88       | 5           | CUST1   |
| CQ88       | 6           | P       |
| CQ22       | 5           | CUST2   |
| CQ22       | 6           | P       |

我的产品表的结构类似

| warehouse | product | customer | location |
| --------- | ------- | -------- | -------- |
| 55        | ABC DEF | CUST1    | P        |

我建立的查询是

select p.*, a.account_no from products p
left join accounts a on 
    (a.content = p.customer and a.line_number = 5)
    and
    (a.content = p.location and a.line_number = 6);

不幸的是account_no的结果为NULL

| warehouse | product | customer | location | account_no |
| --------- | ------- | -------- | -------- | ---------- |
| 55        | ABC DEF | CUST1    | P        |            |

这不是我追求的结果。

我在做什么错了?

谢谢

编辑:

我的预期输出是:

| warehouse | product | customer | location | account_no |
| --------- | ------- | -------- | -------- | ---------- |
| 55        | ABC DEF | CUST1    | P        | CQ88       |

由于我的帐户表在line_number 5为'CUST1'和line_number 6 ='P'时仅具有account_no ='CQ88'

4 个答案:

答案 0 :(得分:0)

问题出在您的ON条件上:

(a.content = p.customer and a.line_number = 5)
and
(a.content = p.location and a.line_number = 6);

由于您使用过AND运算符,因此两个条件都必须为True才能找到匹配项。而且Accounts表中没有一行具有5和6的行号。

因此,将and更改为or。它应该可以解决您的问题。

让我知道它是否有效。

答案 1 :(得分:0)

我猜你想要两个联接:

select p.*,
       a5.account_no as customer_account_no,
       a6.account_no as location_account_no
from products p left join
     accounts a5
     on a5.content = p.customer and
        a5.line_number = 5 left join
     accounts a6
     on a6.content = p.location and
        a6.line_number = 6;

答案 2 :(得分:0)

我解决了。

我需要重新组织我的帐户表,以便每个account_no一行

https://www.db-fiddle.com/f/q6GJFqFqrNrDgMd3fnmEwG/6

然后我执行了一个简单的连接

select p.*, new_accounts.account_no from products p
left join (      
select distinct a.account_no, concat(b.content , '-',c.content) as 'custloc' from accounts a
left join (select * from accounts where line_number = 5) b on a.account_no = b.account_no
left join (select * from accounts where line_number = 6) c on a.account_no = c.account_no
  ) new_accounts ON concat(p.customer,'-',p.location) = new_accounts.custloc;

产生

| warehouse | product | customer | location | account_no |
| --------- | ------- | -------- | -------- | ---------- |
| 55        | ABC DEF | CUST1    | P        | CQ88       |

答案 3 :(得分:-1)

select p.*, a.account_no from products p
inner join accounts a on 
    (a.content = p.customer and a.line_number = 5)
inner join accounts b on 
    (b.content = p.location and b.line_number = 6) and a.account_no  = b.account_no