使用“NOT IN”查询过滤问题

时间:2012-07-16 06:34:20

标签: mysql filtering

我正在开展一个小项目,就像技术人员的议程一样,每个技术人员都被分配到日常议程中。

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

我尝试的查询是:

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');

1 个答案:

答案 0 :(得分: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