0

有两个表JOBWORKER

工作表

  • 乔比

工人表

  • 工人ID
  • JOBID(来自 JOB 表的 FK)
  • 假期(“Y”或“N”)

通过这两个表,我想找到一个现在没有分配工人的工作列表。我进行了以下查询,但由于聚合函数SUMCASE WHEN.

有比这更好的查询吗?

SELECT
    SUBQUERY.JOBID
FROM
(
    SELECT
        JOBID,
        SUM
        (
            CASE WHEN
                VACATION = 'N'
            THEN 1
            ELSE 0
            END
        ) NUM_WORKERS
    FROM
        JOB
    LEFT JOIN
        WORKER
    ON
        JOB.JOBID = WORKER.JOBID
    GROUP BY
        JOB.JOBID
) SUBQUERY
WHERE
    SUBQUERY.NUM_WORKERS = 0
4

3 回答 3

1

Select * From job Where jobid not in(从工人中选择不同的jobid)

而已。

于 2013-10-20T13:00:22.153 回答
1

看看这里,希望对你有帮助

SELECT JOBID 
FROM JOB 
WHERE JOBID NOT IN (
    SELECT j.JOBID 
    FROM JOB j 
    JOIN WORKER w ON j.JOBID = w.JOBID
    WHERE w.VACATION = 'N'
    GROUP BY j.JOBID
)

Sqlfiddle 示例:示例

于 2013-10-20T13:00:52.317 回答
0

我会用这个:

SELECT j.jobid 
FROM job AS j
WHERE NOT EXISTS
      ( SELECT 1
        FROM worker AS w 
        WHERE w.vacation = 'N'
          AND w.jobid = j.jobid
      ) ;

或这个:

SELECT j.jobid 
FROM job AS j

EXCEPT

SELECT w.jobid
FROM worker AS w 
WHERE w.vacation = 'N' ;
于 2013-10-20T22:11:08.037 回答