开发者

MS ACCESS 2010 - trying to write a query to avoid duplication in a linking table

开发者 https://www.devze.com 2023-03-09 11:43 出处:网络
This is my first question so I\'m going to be very thorough. Bear with me. I am building a database for beers and have created a linking table that allows me to suggest similar beers (either by taste

This is my first question so I'm going to be very thorough. Bear with me.

I am building a database for beers and have created a linking table that allows me to suggest similar beers (either by taste or some other quality). The original table uses beerID as the primary key and in the linking table I've created a composite primary key from the foreign keys beerID1 and beerID2 by loading in the beerID 开发者_StackOverflowtwice. It's working well so far, except that when I select:

beerID1 = Dechutes IPA, beerID2 = Rogue IPA

-and then in another row-

beerID1 = Rogue IPA, beerID2 = Dechutes IPA

As you can see I have a problem with duplicate data and I'm not too familiar with SQL to get down to the nitty gritty in how to fix this. Any ideas that a layman can use? I'm thinking of some form of validation or query... but can't seem to navigate too far along.


You actually want to normalise that a little more. Check out http://en.wikipedia.org/wiki/First_normal_form

I think what your are doing is:

Beer
BeerID  BeerName  BeerManufacturer
------  --------  ----------------
1       Beer1     Brewer 1
2       Beer2     Brewer 1
3       Beer3     Brewer 2
4       Beer4     Brewer 3

AltBeer
AltBeerID  BeerID  BeerID1  BeerID2  BeerID3
---------  ------  -------  -------  -------
1          1       3        4
2          2       5
3          4       7

Instead you want to have just one column for Alternate Beers. In this case, AltBeer becomes

AltBeer
AltBeerID  BeerID  AltBeer
---------  ------  -------
1          1       3        
1          1       4        
2          2       5
3          4       7

Then doing a join on Beer and AltBeer (based on BeerID) will give you a list of BeersID that are similar to the original beer. You can the details of the Alternate beers by joining with Beer again (based on BeerID and AltBeer)

SELECT beer.beermanufacturer,
       beer.beername,
       beer_1.beername         AS recbeer,
       beer_1.beermanufacturer AS recbeerman
FROM   (altbeer
       INNER JOIN beer
         ON altbeer.beerid = beer.beerid)
       INNER JOIN beer AS beer_1
         ON altbeer.altbeer = beer_1.beerid;  

The result being something like this (no dups, guarenteed)

BeerName    BeerManufacturer   RecBeer     RecBeerMan
--------    ----------------   -------     -----------
Beer1       BeerMan1           Beer3       BeerMan2
Beer1       BeerMan1           Beer4       BeerMan3

(Of course, if we were normalising this all correctly, we've also split Beer Manufacturer into its own table since there's a many-to-1 relationship between beer and manufacturer.)

0

精彩评论

暂无评论...
验证码 换一张
取 消