简体   繁体   中英

Select name of two foreign keys referring to same primary key table

I have an inventory transaction table Transaction_Log

The columns are log_id , to_warehouse , from_warehouse , both FOREIGN KEYs referencing to the warehouse table OWHS with columns whs_id , whs_name

I need to output with these columns: log_id , to_warehouse_name , from_warehouse_name

Tried this

SELECT t.log_id, w1.whs_name AS to_warehouse_name, w2.whs_name from_warehouse_name
FROM OWHS w1, OWHS w2
 INNER JOIN Transaction_Log t ON w1.whs_id = t.to_warehouse AND w2.whs_id = t.from_warehouse

but it throws an error

invalid table name: w1.whs_id

I'm not sure whether the query is correct to output what I want, but the error already throws me off.

I use SAP HANA database, but I changed the column names a bit for this post. I'm also returning to database programming after several years, so I apologize if this is a basic question, but my googling returns nothing close to what I want.

Never use commas in the FROM clause. Period. Write the query as:

SELECT t.log_id, w1.whs_name AS to_warehouse_name, w2.whs_name from_warehouse_name
FROM OWHS w1 JOIN
     Transaction_Log t
     ON w1.whs_id = t.to_warehouse JOIN
     OWHS w2
     ON w2.whs_id = t.from_warehouse;

Although you could also fix the problem by replacing the , with CROSS APPLY that just confuses the logic. You are looking for two simple JOIN s.

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