Link to home
Start Free TrialLog in
Avatar of CipherIS
CipherISFlag for United States of America

asked on

SQL - Identify where keys are being used to build SQL Statement

I attempted to duplicate the issue I am experiencing.  I have 3 tables (Ship, Items, ItemsShip).  I am trying to resolve a logic issue and write a SQL that will get me the data that I'm looking for.

Item table relates to Ship table by "ShipID".  
ItemShip table relates to Item table by "ItemID" and Ship table by "ShipID".

The logic was written with .NET with regards to how the data is inserted.  I don't understand why ItemShip was created considering that Items table contains a "ShipID" field.

Regardless, I am getting data between Ship and Items.  However, I need to check to see if there is data in ItemsShipped which should be joined.

Should I just do something like

FROM Ship S
INNER JOIN Item I on I.ShipID = S.ShipID
INNER JOIN ItemShip IS ON IS.Item = I.Item
                                           AND IS.Ship = S.SHip
CREATE TABLE #SHIP(
		ShipID	INT,
		Name	VARCHAR(20)
)

CREATE TABLE #ITEM(
		ItemsID	INT,
		ShipID	INT,
		Name	VARCHAR(20)
)

CREATE TABLE #ITEMSSHIP(
		ItemsShipID	INT,
		ItemsID	INT,
		ShipID	INT
)

INSERT INTO #SHIP
(ShipID, Name)
VALUES
(1, 'Ship #1'),
(2, 'Ship #2'),
(3, 'Ship #3'),
(4, 'Ship #4'),
(5, 'Ship #5')

INSERT INTO #ITEM
(ItemsID, ShipID, Name)
VALUES
(1, 1, 'Item #1'),
(2, 4, 'Item #4'),
(3, 5, 'Item #5')

INSERT INTO #ITEMSSHIP
(ItemsShipID, ItemsID, ShipID)
VALUES
(1, 1, 1),
(2, 2, 4),
(3, 3, 5)

SELECT * FROM #SHIP
SELECT * FROM #ITEM
SELECT * FROM #ITEMSSHIP

DROP TABLE #ITEM
DROP TABLE #ITEMSSHIP
DROP TABLE #SHIP

Open in new window

Avatar of Rex
Rex

You can always check the record existence by using join and exists

 IF EXISTS (SELECT 1 FROM #SHIP S
INNER JOIN #Item I on I.ShipID = S.ShipID
INNER JOIN #ITEMSSHIP t ON t.ShipID = S.ShipID)
  BEGIN
        --logic
  END

Open in new window

Avatar of CipherIS

ASKER

I'm looking to get the missing items.
So, you want missing items from #ITEMSSHIP table. Right?
Yes.  I need to get all of the records in ITEM.

Whether joining from Item.ShipID to Ship.ShipID or ItemShip.ShipID = Ship.ShipID and ItemShip.itemID = Items.ItemID.
Wht output you need from sample input you have given ?
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial