无法确定任务的SQL查询

时间:2017-07-29 08:42:11

标签: sql-server

我有以下表格的数据库

登录表:

CREATE TABLE [dbo].[Login]
(
    [username] [nvarchar](100) NOT NULL,
    [password] [nvarchar](50) NOT NULL,
    [user_type] [nchar](10) NOT NULL,
    [id] [int] IDENTITY(1,1) NOT NULL,
    [isDelete] [bit] NOT NULL,
)

测试表:

CREATE TABLE [dbo].[Test]
(
    [TestId] [int] IDENTITY(1,1) NOT NULL,
    [TestName] [nvarchar](100) NOT NULL,
    [UserId] [int] NOT NULL,
    [isDelete] [bit] NOT NULL,
)

问题表:

CREATE TABLE [dbo].[Questions]
(
    [Qid] [int] IDENTITY(1,1) NOT NULL,
    [Tid] [int] NOT NULL,
    [Qtype] [int] NOT NULL,
    [Question] [nvarchar](max) NOT NULL,
    [isDelete] [bit] NULL,
)
  • Login.id是外键并引用Test.UserId
  • Test.TestId是外键,引用Questions.Tid

我的问题是:我想提取Login.usernameTest.TestName以及每次测试的问题数量,例如:我希望所有测试都存在,每个测试的问题数量(即使为0)。

我尝试了以下查询

select 
    Test.TestId, Test.TestName, COUNT(Questions.Tid) as 'No.Of Questions' 
from 
    Test, Questions
where  
    Test.TestId = Questions.Tid and
    Questions.isDelete <> 'true'
group by 
    TestId, TestName

但此查询仅返回问题表中至少存在单个问题的测试。

我希望所有测试都是强制性的,然后是每次测试的问题。

1 个答案:

答案 0 :(得分:0)

您需要使用Left outer join

select T.TestId,T.TestName,COUNT(Q.Tid) as [No.Of Questions]
from Test t
Left Join Questions q
       On Q.isDelete<>'true'
      and T.TestId=Q.Tid
group by TestId,TestName

您当前的语法与Inner Join类似。这就是你得到没有任何问题的测试的原因