简体   繁体   English

连接两个表和两个列

[英]Joining two tables and two columns

I have articles and discounts table. 我有articlesdiscounts表。 Articles could have family and subfamily (or not, could be blank). Articles可以有家庭和亚科(或可以空白)。

Articles: 文章:

id | name | price | family | subfamily
1  | art1 | 5     | F01    | A02
2  | art2 | 5.5   | F02    |

Discounts 打折

id | customer_id | family | subfamily | discount
1  | ABC123      | F01    | A02       | 40%
2  | CBD321      | F02    |           | 30%

I need to retrieve articles with their discount based on: customer_id (customer who will do order) family and subfamily. 我需要根据以下折扣条件检索商品: customer_id (将要下订单的客户)家庭和子家庭。 Articles could have discount based on his family only (subfamily is blank) or on his family and subfamily but both need to be associed to customers id on the table. 物品可以仅基于他的家庭(子家庭为空白)或根据他的家庭和子家庭而享有折扣,但是两者都需要与桌子上的客户ID相关联。 If one articles doesnt match anything, his discount would be null for that customer. 如果一件商品与任何商品都不匹配,则该客户的折扣将为空。

How can I do this? 我怎样才能做到这一点? I tried this, but only can retrieve rows as if it were INNER JOIN 我试过了,但是只能像INNER JOIN一样检索行

SELECT
  a.*,
  d.discount
FROM articles a
LEFT JOIN discounts AS d
  ON a.family = d.family
  AND a.subfamily = d.subfamily
WHERE d.customer_id = 'ABC123'

Move the discounts condition from WHERE to ON to get true LEFT JOIN result: 将折扣条件从WHERE移到ON以获得真实的LEFT JOIN结果:

SELECT a.*, d.discount
FROM articles a
LEFT JOIN discounts AS d ON a.family = d.family AND a.subfamily = d.subfamily
  AND d.customer_id = 'ABC123'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM