您可以將報表與機器一起留在表格中。
並加入機器ID和週數。
如果沒有匹配,則報告ID將爲空。
例如:
一些測試數據:
drop table if exists machineryreport;
create table machineryreport (ID int, NAME varchar(30), `MACHINE ID` varchar(4), HOURS int, SUBMITTED BOOLEAN, `DATE` date, `WEEK NO` int);
insert into machineryreport (ID, NAME, `MACHINE ID`, HOURS, SUBMITTED, `DATE`, `WEEK NO`) values
(175, 'John Doe', 'H92', 2600, True, '2017-03-05 15:36', 21),
(176, 'Jane Doe', 'H93', 2700, True, '2017-03-05 15:38', 21),
(177, 'Jake Doe', 'H95', 2900, True, '2017-03-06 15:42', 21);
drop table if exists machinery;
create table machinery (ID int, `MACHINE ID` varchar(4), MAKE varchar(30), MODEL varchar(8));
insert into machinery (ID, `MACHINE ID`, MAKE, MODEL) values
(1,'H92','Alderado','H1254'),
(2,'H93','Ricoh','H1254'),
(3,'H94','Consuela','H1254'),
(4,'H95','Josep','H1254');
使用LEFT JOIN:
select m.*
from machinery m
left join machineryreport r
on (m.`MACHINE ID` = r.`MACHINE ID` and
r.`WEEK NO` = 21)
where r.ID is null;
或者使用NOT IN的子查詢:
select *
from machinery
where `MACHINE ID` not in (
select distinct `MACHINE ID`
from machineryreport
where `WEEK NO` = 21
);
或者使用NOT EXISTS:
select *
from machinery m
where not exists (
select 1
from machineryreport r
where m.`MACHINE ID` = r.`MACHINE ID`
and r.`WEEK NO` = 21
);
返回:
ID MACHINE ID MAKE MODEL
-- ---------- ---- -----
3 H94 Consuela H1254
見LEFT JOIN ... WHERE ... IS NULL。仍在掙扎?請參閱https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query – Strawberry