SQL:从不包含另一个表的值的表中选择数据

时间:2017-11-10 13:00:29

标签: mysql sql select subquery

我有一些表格:

CREATE TABLE `entidade_pessoa_avaliacao` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `idEntidade_pessoa` int(10) unsigned NOT NULL,
  `idSemana` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idEscola_Matriculado_idSemana` (`idEntidade_pessoa`,`idSemana`),
  KEY `idEscola_Matriculado` (`idEntidade_pessoa`),
  KEY `idSemana` (`idSemana`),
  CONSTRAINT `FK_smsescola_escola_acao_smsescola_escola_matriculado` FOREIGN KEY (`idEntidade_pessoa`) REFERENCES `entidade_pessoa` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `FK_smsescola_escola_matriculado_avaliacao_smsescola_semana` FOREIGN KEY (`idSemana`) REFERENCES `semana` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=115 DEFAULT CHARSET=utf8;


INSERT INTO `entidade_pessoa_avaliacao` (`id`, `idEntidade_pessoa`, `idSemana`) VALUES
    (1, 1, 1),
    (2, 2, 1),
    (3, 3, 1),
    (4, 1, 2),
    (5, 2, 2),
    (6, 3, 2);


CREATE TABLE  `semana` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nome_curto` varchar(250) NOT NULL,
  `inicio` date NOT NULL COMMENT,
  `termino` date NOT NULL COMMENT,
  `idDimensao` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idDimensao` (`idDimensao`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8;


INSERT INTO `semana` (`id`, `nome_curto`, `inicio`, `termino`) VALUES
    (1, 'Faltas', '2017-10-24', '2017-11-14'),
    (2, 'Tarefas','2017-11-07', '2017-11-14'),
    (3, 'Participacao','2017-11-07', '2017-11-14');

我需要根据日期确定哪个WEEK不在student_avaliation表中。例如,我该怎么做才能知道哪周没有在week.end = '14 / 11/2017'中注册?

我知道我必须使用NOT EXISTS,但我不知道该怎么做。

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

这是你想要实现的吗?只是一个随机尝试。

SELECT * FROM (SELECT A.ID,A.START,A.ENDDATE,B.ID Z FROM WEEK A
LEFT OUTER JOIN student_avaliation B
ON A.ID=B.IDWEEK) AA
WHERE AA.Z IS NULL
AND AA.ENDDATE='14/11/2017';

OR

select a.* from week a where not exists  (select * from student_avaliation b
where a.id=b.idweek);

答案 1 :(得分:0)

如果您只是想要返回未注册的一周,我相信这会给您带来结果:

SELECT * 
FROM dbo.[week] w
WHERE NOT EXISTS (
  SELECT * FROM dbo.student_avaliation sa
  WHERE w.id = sa.idWeek)

我使用SQLFiddle来准备数据: http://sqlfiddle.com/#!6/c92c45/5

这是另一次尝试...如果你想知道的是周是否有任何注册(student_avaliation表中的一个条目),那么请加入并将其汇总:

SELECT w.id
, w.start
, w.[end]
, w.name
, CASE WHEN sa.id is null then 'Not Registered' else 'Registered' end as WeekRegistered
FROM dbo.[week] w
LEFT JOIN dbo.student_avaliation sa
    ON w.id = sa.idWeek
GROUP BY w.id
, w.start
, w.[end]
, w.name
, CASE WHEN sa.id is null then 'Not Registered' else 'Registered' end
ORDER BY w.id