简体   繁体   中英

Joining two tables and two columns

I have articles and discounts table. Articles could have family and subfamily (or not, could be blank).

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. 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. 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

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:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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