Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Find Related Items Help

$
0
0

I have two tables: (condensed version of Subject) Subject and MessageSubject

CREATE TABLE [dbo].[Subject](
	[SubjectID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nchar](80) NULL,
	[Active] [bit] NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[MessageSubject](
	[MessageSubjectID] [int] IDENTITY(1,1) NOT NULL,
	[MessageID] [int] NOT NULL,
	[SubjectID] [int] NOT NULL
) ON [PRIMARY]	

Not shown is the table 'Message' but every message has one or more subjects (MessageSubject entries)

What I need to do is find all the subjects that were posted to a message 'with' a a given subject, not including the given SubjectID.


My guess is a #temp table or CTE or something is the way to do it, but I can't seem to find out how to do in SQL:

The procedure below is the format I need it to be (if possible) but here is what I am doing in C# code now:

I currently find all the messages for a given subject:

Then I have to query all the MessageSubject (subjects) for each message;

IF any subjects were found for a message other than the source SubjectID (related subjects) I check my list of subjects and if the index of the new related subject is not found I add it to the list.

This means I am performing ('x' + 1) number of queries for each Subject where 'x' = the number of messages and 1 query to find all the messages for the subject.

I know there has to be a way to find to find the 'Related Subject', but I can't seem to get my head around it.

Any help is appreciated, thanks.

Create PROCEDURE [dbo].[Subject_FindRelatedSubjects]

    -- SubjectID Parametere
    @SubjectID int

AS
BEGIN

    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON

    -- Begin Select Statement
    Select [Active],[Name],[SubjectID]
	
    -- From tableName
    From [Subject] s Inner Join [MessageSubject] ms on s.SubjectID = ms.SubjectID

    -- Find Subjects That Were Posted 'With' the SubjectID given
    Where ...

END






Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>