缩短嵌套SQL查询

时间:2013-12-24 16:16:48

标签: sql sql-server database sql-server-2008 database-design

我根据名词(主键)&amp ;;创建了一个数据库库来存储答案。动词(子密钥)。

表格:

questionkey: to store clauses/verbs
mainkey: to store nouns 
answer: to store answers (links answer to questionkey - one to many)
answerkey: links mainkey to answerid (many to many)

我想缩短/优化我的SQL查询,目前我正在使用它:

SELECT answer FROM answer WHERE questionkeyid = 
(SELECT similarid FROM questionkey WHERE questionkeyword = 'define') 
AND answerid = 
    (SELECT answerid FROM answerkey WHERE answerkey.mainkeyid = 
        (select mainkeyid from mainkey where mainkeyword = 'chemistry'));

我是新人。 &安培;如果他们可以工作,不知道如何申请加入

原始数据库:

CREATE TABLE mainkey (
  mainkeyid INTEGER  NOT NULL    ,
  mainkeyword VARCHAR(30)  NOT NULL    ,
PRIMARY KEY(mainkeyid));
GO

CREATE TABLE questionkey (
  questionkeyid INTEGER  NOT NULL    ,
  similarID INTEGER  NOT NULL  ,
  questionkeyword VARCHAR(30)  NOT NULL    ,
PRIMARY KEY(questionkeyid));
GO

CREATE TABLE answer (
  answerid INTEGER  NOT NULL    ,
  questionkeyid INTEGER  NOT NULL  ,
  Answer VARCHAR(200)  NOT NULL  ,
  Views INTEGER      ,
PRIMARY KEY(answerid),
  FOREIGN KEY(questionkeyid)
    REFERENCES questionkey(questionkeyid));
GO

CREATE TABLE answerkey (
  mainkeyid INTEGER  NOT NULL    ,
  answerid INTEGER  NOT NULL  ,
PRIMARY KEY(answerid, mainkeyid),
  FOREIGN KEY(mainkeyid)
    REFERENCES mainkey(mainkeyid),
  FOREIGN KEY(answerid)
    REFERENCES answer(answerid));
GO

2 个答案:

答案 0 :(得分:1)

我相信你正在寻找JOIN。这句话应该为你做到:

SELECT a.answer 
FROM answer a
JOIN questionkey qk
  ON a.questionkey = qk.similarid
JOIN answerkey ak
  ON a.answerid    = ak.answerid
JOIN mainkey mk
  ON a.mainkeyid   = mk.mainkeyid
WHERE qk.questionkeyword = 'define'
  AND mk.mainkeyword     = 'chemistry'

答案 1 :(得分:0)

这就是我得到的:

SELECT a.answer from answer a join questionkey q on a.questionkeyid=q.similarid join answer key ak on ak.answerid=a.answerid join main key m on m.mainkeyid=ak.mainkeyid
WHERE q.questionkeyword=‘define’ AND m.mainkeyword=‘chemistry’