Jump to content

SQL statement question


Go to solution Solved by Psycho,

Recommended Posts

Hi

 

This has been driving me crazy, I have the following tables:

 

Parts:

Part_ID

p1
p2
p3
p4
p5

 

 

Store:

Store_ID

s1
s2
s3
s4

 

Stocks:

Part_ID | Store_ID
p1          s1
p2          s1
p3          s1
p4          s1
p5          s1
p1          s2
p2          s2

 

 

Any what I am trying to do is to get a list of ALL store_IDs which do not stock all products.

 

So I need to check inside the Stocks table to see if for each Store_ID that each instance of Product_ID exists for that Store.

 

Any ideas? :)

 

Link to comment
https://forums.phpfreaks.com/topic/275764-sql-statement-question/
Share on other sites

  • Solution

Maybe not the most efficient, but this works

 

This will return just the store IDs that do not carry all the parts

 

SELECT s.store_id
FROM store AS s
JOIN parts AS p
LEFT JOIN `stocks` AS st
   ON  s.store_id = st.store_id
  AND  p.part_id = st.part_id
WHERE st.store_id IS NULL
GROUP BY s.store_id

 

Or, if you want to include the list of parts each store does not carry, then include the part_id in the SELECT clause and remove the GROUP BY.

 

SELECT s.store_id, p.part_id
FROM store AS s
JOIN parts AS p
LEFT JOIN `stocks` AS st
   ON  s.store_id = st.store_id
  AND  p.part_id = st.part_id
WHERE st.store_id IS NULL
-- GROUP BY s.store_id
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.