Home > database >  sql left join with multiple same table question
sql left join with multiple same table question

Time:10-27

I have the same table with different dates. I need to pull orders year by year according to this table with a single sql. I have 3 table in database.

COMPANY_ORDERS
ID | ORDER_DATE | SHIP_ID
1  | 2021-1-1   | 3
2  | 2020-1-1   | 3

COMPANY_2020_SHIPS
ID | SHIP_DATE
3  | 2020-1-1

COMPANY_2021_SHIPS
ID | SHIP_DATE
3  | 2021-1-1

My problem is different dated SHIPS table with starting same id. How can i left join this orders with ships ? Thanks.

SELECT * FROM COMPANY_ORDERS AS CO
LEFT JOIN COMPANY_WHAT_THE??_SHIP AS S ON S.SHIP_ID=CO.SHIP_ID
//if i write 2020_SHIPS thats wrong, 2021_SHIPS to..

CodePudding user response:

You can add another condition for date year like this:

SELECT * FROM COMPANY_ORDERS AS CO
LEFT JOIN COMPANY_WHAT_THE??_SHIP AS S ON S.SHIP_ID=CO.SHIP_ID AND CO.ORDER_DATE = S.SHIP_DATE

CodePudding user response:

Well, it's not best of designs, as already stated in comments, but given that you also would need to put condition regarding a year (since you have "yearly tables"):

SELECT * FROM COMPANY_ORDERS AS CO
LEFT JOIN COMPANY_2020_SHIP AS S20 ON 
    S20.SHIP_ID = CO.SHIP_ID 
    AND YEAR(CO.ORDER_DATE) = 2020
LEFT JOIN COMPANY_2021_SHIP AS S21 ON
    S21.SHIP_ID = CO.SHIP_ID
    AND YEAR(CO.ORDER_DATE) = 2021

So, if order date is from year 2020, then join table for year 2020, etc.

  •  Tags:  
  • sql
  • Related