How to find ID not in the master ID table

只愿长相守 提交于 2019-12-12 05:34:22

问题


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



来源:https://stackoverflow.com/questions/15285478/how-to-find-id-not-in-the-master-id-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!