How to find ID not in the master ID table

2019-08-25 13:15发布

问题:

Let's say I have a master table for Products, and another table which keeps lists of ProductIDs.

  Table name: Products  
 --------------------
 ProductID, Title, Price  
       1, Title 1, 12.00  
       2, Title 2, 15.00  
       4, Title 4, 11.50  
       8, Title 8, 13.89  
       11, Title 11, 12.00  

     Table name: ListOfProducts  
      --------------------------
       SomeID, ProductIDs  

         34, 4,8,1  
         35, 8,10,2  

Now, you can see that in the table ListOfProducts, record with SomeID=35, the list of products is 8,10,2. How can I use SQL to quickly find out the invalid ProductID 10, since it is not in the master table Products?

My program is actually in classic ASP (legacy), and the database is in MS SQL. I can do a loop in ASP to iterate through the records in ListOfProducts, but how do I use a quick SQL to find any invalid ProductID? In this case, when the program loop to record 35, the script should return ProductID 10.

This looks really simple. But I just couldn't think of a good solution. Can this be done? Please help!

Thank you.

回答1:

You should not store IDs as a comma seperated list, this seems more like a many-to-many relation. You should have a table like:

SomeID | ProductID
-------------------
34     | 4
34     | 8
34     | 1
35     | 8
35     | 10
35     | 2

If you really must use a comma seperated list then you need to create some sort of split function