开发者

How to select IDs from a table if two conditions in other tables match

开发者 https://www.devze.com 2023-01-13 19:39 出处:网络
I am developing a user feedback system using ASP.NET and C#. I have multiple tables and am trying to populate dropdown lists so that the feedback can be filtered.

I am developing a user feedback system using ASP.NET and C#. I have multiple tables and am trying to populate dropdown lists so that the feedback can be filtered.

My tables:

CREATE TABLE tblModules
(
Module_ID nvarchar(10) PRIMARY KEY,
Module_Title nvarchar(MAX) NOT NULL
);

CREATE TABLE tblQuestions
(
Q_ID int PRIMARY KEY IDENTITY(1,1),
Question_Text varchar(1000) NOT NULL

);

CREATE TABLE tblFeedback
(
Submission_ID int PRIMARY KEY IDENTITY(1,1),
Username varchar(100) NOT NULL,
Domain varchar(50) NOT NULL,
DateTime_Submitted datetime NOT NULL
Module_ID nvarchar(10)
FOREIGN KEY (Module_ID) REFERENCES tblModules (Module_ID);
);

CREATE TABLE tblAnswers
(
Q_ID int NOT NULL,
Submission_ID int NOT NULL,
Answer_Text varchar(max),
FOREIGN KEY (Q_ID) REFERENCES tblQuestions(Q_ID),
FOREIGN KEY (Submission_ID) REFERENCES tblFeedback(Submission_ID)
);

I have two dropdown lists. First one is populated with all modules from a table. The second needs to be populated with Questions from tblQuestions but only if any answers to it exist (therefore if the Question ID 'Q_ID' exists in tblAnswers).

I can get the selectedModuleID from the first dropdown list. I have a List of all Questions referenced by Q_ID in tblAnswers. How do I crossreference this list with the module ID?

Each feedback submissi开发者_运维技巧on gets a Submission ID and Module ID.


You want:

  • questions that have answers
  • questions that have a module parent (via tblfeedback)

So, my guess at what you want:

SELECT
   *
FROM
   tblQuestions Q
WHERE
   EXISTS (SELECT *
      FROM
          tblAnswers A
          JOIN
          tblFeedback F ON A.Submission_ID = F.Submission_ID
      WHERE
          Q.Q_ID = A.Q_ID AND F.Module_ID = @moduleID)


This should do the trick...

SELECT Q_ID, Question_Text tblQuestions a 
WHERE EXISTS (SELECT NULL FROM tblAnswers a WHERE a.Q_ID = q.Q_ID)
0

精彩评论

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