0

我的数据库中有三个表

员工表

  • 员工 ID (PK)

问题表

  • 启德(PK)
  • 问题

问卷

  • QuestionnaireId (PK)
  • QId (FK)
  • 员工 ID (FK)
  • 回复
  • 细节

这是我自己编写的 SQL 查询,但它产生了我不需要的输出

 Select q.qid,e.employeeId, q.Question, eq.response 
 from employee e 
 cross join Question q
 left outer join employeequestionnaire eq on q.Qid= eq.Qid
 where e.employeeId = 1

这是输出

             Qid   EmployeeId        Question       Response 
             "1"       "1"          "Question1"     "0"
             "1"       "1"          "Question1"     "1"
             "2"       "1"          "Question2"     "1"
             "2"       "1"          "Question2"     "0"
             "3"       "1"          "Question3"     "1"
             "4"       "1"          "Question4"     NULL

但我需要这种输出

             Qid    EmployeeId       Question       Response  
             "1"       "1"          "Question1"     "0"
             "2"       "1"          "Question2"     "1"
             "3"       "1"          "Question3"     "1"
             "4"       "1"          "Question4"     NULL

我是 SQL 的新手,对不起我的示例查询..

4

1 回答 1

0

假设employeequestionnaire有employeeID 字段,则不需要该employee表。我认为你可以这样做:

Select q.qid, eq.employeeId, q.Question, eq.response 
from Question q left outer join
     employeequestionnaire eq
     on q.Qid= eq.Qid and
        eq.employeeId = 1

请注意,我将where子句移到了on子句中。这在使用left outer join.

如果您想包含该表中有关员工的信息,您可以使用 not cross join

Select q.qid, eq.employeeId, q.Question, eq.response 
from Question q left outer join
     employeequestionnaire eq
     on q.Qid= eq.Qid and
        eq.employeeId = 1 left outer join
     employees e
     on e.EmployeeID = eq.EmployeeID
于 2012-12-26T14:17:35.350 回答