系统:Windows7,Access 2003,.mdb文件,C#语言,VS 2010
我正在使用OleDbCommand进行查询,所以我用字符串编写完整的sql查询。
Table Survey (Id)
Table Questions (Id,IdSurvey)
Table Answers (Id,IdQuestion)
表格被简化为仅显示相关数据
假设1项调查有1个问题 假设1个问题有0..n个答案
我想只选择问题3中有答案1和/或2的调查,我该怎么办?
当前(和差)解决方案:
SELECT surv.Name FROM Survey surv WHERE
(1 IN (SELECT answ.Number FROM Answers answ, Questions quest
WHERE quest.Id = 3 AND quest.IdSurvey = surv.Id)
AND/OR
(2 IN (SELECT answ.Number FROM Answers answ, Questions quest
WHERE quest.Id = 3 AND quest.IdSurvey = surv.Id)))
这看起来像垃圾,所以我很感激帮助。
提前致谢。
修改
我提出了更好的解决方案:
对于 1 OR 2 ,此处给出的解决方案足够(对于非常简单的逻辑表达式)。谢谢你们
对于 1 AND 2 ,我创建了另一个解决方案,我认为看起来有点好(再次,对于非常简单的逻辑表达式)
SELECT surv.Name FROM Survey surv WHERE EXISTS
(SELECT COUNT(*) FROM Answers answ, Questions quest
WHERE quest.Id = 3 AND answ.Number IN (1,2) HAVING COUNT(*) > 1)
HAVING 子句中的“ 1 ”意味着至少需要两行,并且由于答案不会针对相同的问题重复,因此这必然意味着至少答案 1 AND 2 存在于查询的问题中。
嗯,处理更复杂的逻辑表达式时, OR 解决方案和 AND 解决方案都很糟糕,例如(1 AND(2 OR(4 AND) (6 OR 7)))),事实是,它不太可能需要这样的复杂性,但我希望是安全的。对我来说理想的解决方案是:
SELECT surv.Name FROM Survey surv WHERE
(1 IN (SELECT answ.Number FROM Answers answ, Questions quest
WHERE quest.Id = 3 AND quest.IdSurvey = surv.Id) AS CANT_DO_THIS
AND/OR
(2 IN CANT_DO_THIS) AND/OR 5 IN CANT_DO_THIS AND/OR 3 NOT IN CANT_DO_THIS)
答案 0 :(得分:0)
SELECT surv.Name FROM Survery surv
INNER JOIN Questions quest ON surv.ID = quest.IDSurvey
INNER JOIN Answers answ ON quest.ID = answ.IDQuestion
WHERE quest.ID = 3 AND answ.Number IN (1, 2)
这将在每次调查中返回一行(因为您只链接问题ID 3和该问题的单个答案),并且仅针对问题3的答案为1或2的调查。
注意:我不清楚你如何加入数据模型中的问题和答案表,所以我假设Answers表有一个外键回到IDQuestion的问题。
答案 1 :(得分:0)
Select ...
From Survey As
Where Exists (
Select 1
From Questions As Q1
Join Answers As A1
On A1.IdQuestion = Q1.Id
Where Q1.IdSurvey = S.Id
And Q1.Id = 3
And A1.Id In(1,2)
Having Count(*) = 2
)