简体   繁体   中英

sql left join with multiple same table question

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

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

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.

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