简体   繁体   中英

Joining 3 tables & inserting in a 4th table in SQL server

I am joining 3 tables - items , sales , & purchase .

And then, inserting the combined data into a 4th table FULL_DETAIL_OF_ITEMS .

ITEMS table has columns : ITEM_CD, ITEM_NM, COM_CD, SALE_RT, PURCH_RT, MRP

SALES table has columns : ITEM_CD, ITEM_NM, SALE_QTY

PURCHASE table has columns : ITEM_CD, ITEM_NM, PURCH_QTY

FULL_DETAIL_OF_ITEMS table has columns :

ITEM_CD, ITEM_NM, COM_CD, SALE_RT, PURCH_RT, MRP, SALE_QTY, PURCH_QTY

The query is:

insert into FULL_DETAIL_OF_ITEMS
  SELECT
     Items.Item_CD, 
     Items.Item_NM , 
     ITEMS.COM_CD, 
     ITEMS.SALE_RT, 
     ITEMS.PURCH_RT, 
     ITEMS.MRP, 
     SALES.SALE_QTY, 
     PURCHASE.PURCH_QTY
  FROM items
  JOIN sales on ITEMS.ITEM_CD = sales.ITEM_CD 
  JOIN purchase on items.ITEM_CD = purchase.ITEM_CD

Items table is filled but sales & purchase tables are empty, so on executing the above query nothing happens? Why so?

At least it should insert rest of the columns from the items table into the 4th table.

It finds that in sales table - sale_qty , & in purchase table, purch_qty is empty, so it should fill null in these columns in the final table & fill rest of the columns as they are picked from item table which consists data so it should fill that.

But its not doing so?

According to the definition of JOIN, ITEM_CD in item table is not matching with the ITEM_CD column of the sales & purchase table as it is empty in both, so this is the reason.

But I want that rest of the data is inserted in the 4th table, then is there any way to do this?

You need to change those join statements to left join .

By default, a join is an "inner join", which means that only rows that exist on both sides of the join will be included. A "left join" includes all rows on the "left" side of the join.

Example:

from items
left join sales on ITEMS.ITEM_CD =sales.ITEM_CD
left join purchase on items.ITEM_CD =purchase.ITEM_CD

You can minimize your query using a select into statement which will, by default, creates a new table at run time.

select  Items.Item_CD,Items.Item_NM,Items.COM_CD,Items.Mrp,Items.Purchase_RT,Items.Sale_RT,
      purchase.Purchase_QTY,Sales.Sale_QTY
into full_details_of_items
from Items
inner join purchase
inner join Sales 
on purchase.Item_CD=Sales.Item_CD
on items.Item_CD=purchase.Item_CD

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