查询2个表来查找结果

时间:2012-07-26 17:54:44

标签: mysql

我有一个提交表,其中包含一个名为submissionID(主键)的字段

我有一个答案表,其中有一个名为submissionID的字段

我的目标是找到提交ID,其中16和39都得到了回答

以下是我到目前为止所做的但似乎并没有做我想要的......也许我在JOIN的错误路径上?也许我需要内心选择?

SELECT submissions.*, answer.answer, answer.submissionID FROM submissions JOIN answer USING(submissionID) WHERE (answer = 16 AND answer = '39')

这是表格提交的方案

CREATE TABLE `submissions` (
  `submissionID` int(11) NOT NULL AUTO_INCREMENT,
  `sID` int(11) NOT NULL,
  `sendInfoTo` text NOT NULL,
  `userIP` text NOT NULL,
  `sendNotificationTo` text NOT NULL,
  PRIMARY KEY (`submissionID`)
) ENGINE=MyISAM AUTO_INCREMENT=1343314525 DEFAULT CHARSET=latin1$$

9'

HEREE是答案的方案

CREATE TABLE `answer` (
  `aID` int(11) NOT NULL AUTO_INCREMENT,
  `qtID` int(11) NOT NULL,
  `answer` text NOT NULL,
  `submissionID` int(11) NOT NULL,
  PRIMARY KEY (`aID`)
) ENGINE=MyISAM AUTO_INCREMENT=56247 DEFAULT CHARSET=latin1$$

提交表包含唯一提交ID

答案表包含提交的所有答案

所以例如我有一堆问题。问题1的答案可能是16,问题2的答案可能是39,所以我想找到提交ID,其中16和39都被回答

3 个答案:

答案 0 :(得分:0)

这样的事情:

SELECT 
    submissions.*
    , answer.answer
    , answer.submissionID 
FROM 
    submissions 
JOIN answer on submissions.submissionID = answer.submissionID
WHERE
    answer.answer IN (16,39)

答案 1 :(得分:0)

尝试以下查询,这可能对您有帮助..

SELECT s.submissionID  FROM submissions s JOIN answer a USING(submissionID) WHERE a.answer IN (16,39)

答案 2 :(得分:0)

当你的条件为答案= 18且答案= 39永远不成真时,你可以通过以下方式进行OR:

  SELECT submissions.*, answer.answer, answer.submissionID FROM submissions JOIN answer ON  submissions.submissionID = answer.submissionID WHERE answer.answer ='16' OR answer.answer ='39'