To simplify things, I have already created the tables and the data inside of them. The queries to accomplish our tasks will be at the bottom of this post.
Download the IceCreamStore Database:
These files are scripts you can run to create the database and insert the records.
Selecting all the flavors for a specific brand:
To select all the flavors from a specific brand, we will use two techniques: inner joins and a cross reference table. A cross reference table is a table that exists 'between' two tables that creates a link for those tables. It usually holds the primary keys of the original two tables to create a relation between those tables.
To select all flavors for a specific brand:
- USE IceCreamStore;
- GO
- -- Select all flavors from a specific brand.
- SELECT F.Name AS 'Flavor Name'
- FROM dbo.Flavors AS F
- INNER JOIN dbo.xBrandsFlavors AS X
- ON F.flavorID = X.flavorID
- INNER JOIN dbo.Brands AS B
- ON X.brandID = B.brandID
- WHERE B.Name = 'Amul';
In the above query, "Amul" is the name of the brand we want to search for. The query returns all the ice cream flavors that a brand offers.
Selecting all brands that sell a particular flavor:
This query uses the same techniques as selecting the flavors for a specific brand, except it does it in reverse.
To select all brands for a particular flavor:
- USE IceCreamStore;
- GO
- -- Select all brands that sell a specific flavor.
- SELECT B.Name AS 'Brand Name'
- FROM dbo.Brands AS B
- INNER JOIN dbo.xBrandsFlavors AS X
- ON B.brandID = X.brandID
- INNER JOIN dbo.Flavors AS F
- ON X.flavorID = F.flavorID
- WHERE F.Name = 'Vanilla Ice Cream';
In the above query "Vanilla Ice Cream" is the ice cream flavor we want to search for. The query returns all the brands that offer that ice cream flavor.
No comments:
Post a Comment