I have four SQL Server tables. The first two, say tblProducts and tblSiteIds, each have a pointer to tblProviders
tblProducts: prod1 provider1
prod2 provider1
prod3 provider2
tblSiteIds: siteId1 site1 idfromprovider1 provider1
siteId2 site1 idfromprovider2 provider2
siteId3 site2 idfromprovider2 provider2
[site1, site2, point to yet another table tblSites] [siteId? is the internal entry # for that row, idfromprovider is the actual free-text id] So tblSiteIds holds the id for a particular site, from a provider.
A third table, say tblOrders, has a pointer to each of those two:
tblOrder: order1 siteId1 prod1
order2 siteId1 prod2
order3 siteId3 prod2
The issue I'm having is that there should be a rule that the siteId and the product for a given order must point to the same provider (broken in order3 here, since siteId3 comes from provider2, but prod2 comes from provider1), but I'm not sure how to enforce it. Should the tables be designed differently (how?), or it there a way to make this rule work? Thanks!
Here is how to reproduce this problem;
IF OBJECT_ID('tempdb..#tblProducts') IS NOT NULL DROP TABLE #tblProducts
CREATE TABLE #tblProducts (Prod int, Provider int)
INSERT INTO #tblProducts (Prod, Provider)
VALUES (1,1),(2,1),(3,2)
IF OBJECT_ID('tempdb..#tblSiteIds') IS NOT NULL DROP TABLE #tblSiteIds
CREATE TABLE #tblSiteIds (SiteID int, Site int, IDFromProvider int, Provider int)
INSERT INTO #tblSiteIds (SiteID, Site, IDFromprovider, Provider)
VALUES (1,1,1,1),(2,1,2,2),(3,2,2,2)
IF OBJECT_ID('tempdb..#tblOrders') IS NOT NULL DROP TABLE #tblOrders
CREATE TABLE #tblOrders (orderID int,siteId int,prod int)
INSERT INTO #tblOrders (orderID, siteId, prod)
VALUES (1,1,1),(2,1,2),(3,3,2)
/* this shows that for orderID 3 the providers are different */
SELECT
o.orderID
,p.Provider
,s.Provider
FROM #tblOrders o
JOIN #tblProducts p ON o.prod = p.Prod
JOIN #tblSiteIds s ON o.siteId = s.SiteID
tblProducts
andtblSiteIds
tables look completely fine to me, each representing a one-to-many relationship. I am lost with the orders table. Maybe you could describe the logic behind what you think an order represents here?