I was thinking last night of restructuring the way "Related Items" are pulled from the database for one of our sites. Basically at the moment it is upto the client to flag two products as related. I'm thinking of using a new method of tagging the products and then finding related products based on the tags assigned -the general code for this is below but what I want to know is, is using "IN" the most efficient way of doing this?TIATimDECLARE @ItemId intSET @ItemId = 1SELECT COUNT(i.ItemId) AS MatchingTags, i.ItemId, i.ItemNameFROM tst_Items i LEFT JOIN txt_x_Items_Tags x ON i.ItemId = x.ItemIdWHERE x.TagId IN ( SELECT t.TagId FROM tst_Tags t LEFT JOIN txt_x_Items_Tags x ON t.TagId = x.TagId WHERE x.ItemId = @ItemId )GROUP BY i.ItemId, i.ItemNameHAVING i.ItemId <> @ItemIdORDER BY MatchingTags DESC
The testing data:CREATE TABLE [dbo].[tst_Items]( [ItemId] [int] NOT NULL, [ItemName] [nvarchar](50) NOT NULL) ON [PRIMARY]GOCREATE TABLE [dbo].[tst_Tags]( [TagId] [int] NOT NULL, [TagName] [nvarchar](50) NOT NULL) ON [PRIMARY]GOCREATE TABLE [dbo].[txt_x_Items_Tags]( [ItemId] [int] NOT NULL, [TagId] [int] NOT NULL) ON [PRIMARY]GOINSERT INTO tst_Items VALUES (1, 'Test Item 1')INSERT INTO tst_Items VALUES (2, 'Test Item 2')INSERT INTO tst_Items VALUES (3, 'Test Item 3')INSERT INTO tst_Items VALUES (4, 'Test Item 4')INSERT INTO tst_Tags VALUES (1, 'Tag 1')INSERT INTO tst_Tags VALUES (2, 'Tag 2')INSERT INTO tst_Tags VALUES (3, 'Tag 3')INSERT INTO tst_Tags VALUES (4, 'Tag 4')INSERT INTO txt_x_Items_Tags VALUES (1, 1)INSERT INTO txt_x_Items_Tags VALUES (1, 2)INSERT INTO txt_x_Items_Tags VALUES (1, 3)INSERT INTO txt_x_Items_Tags VALUES (2, 1)INSERT INTO txt_x_Items_Tags VALUES (2, 3)INSERT INTO txt_x_Items_Tags VALUES (3, 1)INSERT INTO txt_x_Items_Tags VALUES (3, 2)INSERT INTO txt_x_Items_Tags VALUES (1, 4)INSERT INTO txt_x_Items_Tags VALUES (4, 4)GO
----------------------------I've finally started blogging (all be it badly!)Check it out:http://blogs.thesitedoctor.co.uk/tim/