0

我正在做一个小项目,有点像技术人员的议程,每个技术人员都被分配了一个日常议程。

我正在寻找一个查询,它只显示一个分支中一天没有分配的技术人员(该公司有两个分支:东部和西部)

我试过的查询是:

SELECT *
FROM technicians
WHERE id_tech NOT
IN (    
     SELECT id_tech
     FROM hours
   )
AND branch = 'West'

这个查询返回我想要的,但我不知道如何用日期过滤它,我尝试了很多查询,并返回所有具有重复结果的列。

我的表格是每个技术人员都有任务的小时表:

CREATE TABLE IF NOT EXISTS `hours` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_tech` int(11) NOT NULL,
  `9_30` varchar(140) DEFAULT NULL,
  `10_30` varchar(50) DEFAULT NULL,
  `11_30` varchar(50) DEFAULT NULL,
  `12_30` varchar(50) DEFAULT NULL,
  `1_30` varchar(50) DEFAULT NULL,
  `2_30` varchar(50) DEFAULT NULL,
  `3_30` varchar(50) DEFAULT NULL,
  `4_30` varchar(50) DEFAULT NULL,
  `5_30` varchar(50) DEFAULT NULL,
  `6_30` varchar(50) DEFAULT NULL,
  `comments` varchar(50) DEFAULT NULL,
  `date` text NOT NULL,
  PRIMARY KEY (`id`)
) TYPE=MyISAM  ROW_FORMAT=DYNAMIC;

INSERT INTO `hours` (`id`, `id_tech`, `9_30`, `10_30`, `11_30`, `12_30`, `1_30`, `2_30`, `3_30`, `4_30`, `5_30`, `6_30`, `comments`, `date`) VALUES
(1, 1, 'Router with problems, Customer ID 111', 'Router with problems, Customer ID 111', 'Router with problems, Customer ID 111', 'Router with problems, Customer ID 111', 'Router with problems, Customer ID 111', 'Desktop with problems, Customer ID 121', NULL, NULL, NULL, 'Network problems, Customer ID 121', 'Router with problems, Customer ID 111', '16-07-2012'),
(3, 3, 'Network with problems, Customer ID 111', 'Network with problems, Customer ID 111', NULL, NULL, NULL, NULL, NULL, NULL, 'Network with problems, Customer ID 111', '', 'Didn''t came to work today', '16-07-2012');

和技术人员表:

CREATE TABLE IF NOT EXISTS `technicians` (
  `id_tech` int(11) NOT NULL,
  `name` varchar(50) COLLATE utf8_spanish_ci NOT NULL,
  `branch` varchar(50) COLLATE utf8_spanish_ci NOT NULL,
  PRIMARY KEY (`id_tech`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci ROW_FORMAT=DYNAMIC;


INSERT INTO `technicians` (`id_tech`, `name`, `branch`) VALUES
(1, 'Peter', 'East'),
(2, 'Juan', 'East'),
(3, 'Rick', 'West'),
(4, 'Mario', 'West');
4

1 回答 1

0

将日期比较作为条件检查之一放在LEFT JOIN

SELECT a.*
FROM technicians a
LEFT JOIN hours b ON 
          a.id_tech = b.id_tech AND 
          STR_TO_DATE(b.date, '%d-%m-%Y') = CURDATE()
WHERE a.branch = 'West' AND b.id_tech IS NULL

^ 这将获取当天没有任务的所有技术人员。

-- Get all West branch technicians who have not been assigned within past week

SELECT a.*
FROM technicians a
LEFT JOIN hours b ON 
          a.id_tech = b.id_tech AND 
          STR_TO_DATE(b.date, '%d-%m-%Y') >= CURDATE() - INTERVAL 1 WEEK
WHERE a.branch = 'West' AND b.id_tech IS NULL

如果您想在过去的特定日期进行比较:

-- Get all West branch technicians who have not been assigned on a particular
-- day in the past:

SELECT a.*
FROM technicians a
LEFT JOIN hours b ON 
          a.id_tech = b.id_tech AND 
          STR_TO_DATE(b.date, '%d-%m-%Y') = CAST('2012-06-14' AS DATE)
WHERE a.branch = 'West' AND b.id_tech IS NULL
于 2012-07-16T06:51:19.080 回答