如何从一个表中选择项目,使另一个表中的查询恰好产生一行?

时间:2014-04-07 11:00:12

标签: sql sql-server

我有两个表:JobsJobItems

CREATE TABLE Jobs (
    [JobId] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY
);

Create TABLE JobItems(
    [ItemId] UNIQUEIDENTIFIER NOT NULL,
    [JobId] UNIQUEIDENTIFIER NOT NULL
);

并且对于Jobs中的每一行,JobItems中可以有一行,一行或多行,以使其JobIdJobs中的行匹配,这意味着零,一个或多个“作业”包含该“项目”。

我需要从Jobs中选择行,以便JobItems中只有一行JobIdJobs中的行匹配,并尝试来自{{3}的代码(稍微改动一下):

SELECT JobId, (SELECT Count(ItemId) from JobItems WHERE
     JobItems.JobId=Jobs.JobId) from Jobs

问题是我现在需要以某种方式说我只需要一个匹配的行。所以我尝试为Count(ItemId)

指定一个快捷方式
SELECT JobId, (SELECT Count(ItemId) AS CountItemId from JobItems WHERE
     JobItems.JobId=Jobs.JobId) from Jobs WHERE CountItemId=1

但这会让SQL服务器不满意 - 它说

  

列名CountItemId无效

如何只选择一个匹配的项目?

5 个答案:

答案 0 :(得分:2)

基本的GROUP BY HAVING子句会为你做..

      SELECT Jobs.jobId
      FROM Jobs 
      INNER JOIN JobItems
         ON Jobs.JobId = JobItems.JobId
      GROUP BY Jobs.jobId
      HAVING COUNT(*)=1

答案 1 :(得分:1)

使用此查询:

SELECT JobId, Count(ItemId) from JobItems group by JobId;

答案 2 :(得分:1)

你可以这样做:

select *
from jobs i
where (select count(*) from jobitems ji where ji.jobid = j.jobid) = 1;

但是,如果表作业只包含所有作业ID而不包含任何其他内容,那么您根本不必从表作业中选择:

select jobid
from jobitems 
group by jobid
having count(*) = 1;

答案 3 :(得分:1)

Select jobid
From jobitems 
Group by jobid
Having count(*) = 1;

答案 4 :(得分:1)

您还可以创建临时结果集:

WITH T1 AS (
  SELECT JobId
  FROM Jobs 
),
T2 AS (
  SELECT JobId, Count(ItemId) AS CountItemId 
  FROM JobItems 
  GROUP BY JobID
)

SELECT JobId, CountItemId
FROM T2
WHERE CountItemId = 1