MySQL - 将查询结果与当前表数据进行比较

时间:2016-09-15 22:53:17

标签: mysql statements

我有以下两个表:

表1

|  id |  name |  job    |      start_time      |     end_time          |
| ----| ------| --------| ---------------------| ----------------------|
| 111 |  John |  Janitor|  2016-08-20 00:01:00 |       NULL            |
| 111 |  John |  Janitor|        NULL          |   2016-08-20 00:02:00 |
| 222 |  Sam  |  Valet  |  2016-08-20 00:03:00 |          NULL         |
| 222 |  Sam  |  Valet  |        NULL          |   2016-08-20 00:04:00 |

表2

|  name |  job    |      checkin_time    |
| ------| --------| ---------------------|
|  John |  Janitor|  2016-08-20 00:01:30 |
|  Sam  |  Valet  |  2016-08-20 00:03:30 |
|  Tim  |  Cashier|  2016-09-20 00:01:00 |

以下查询

SELECT id, Table2.name, Table2.job, start_time, Table2.checkin_time, end_time FROM (
SELECT id,name,job, MIN(start_time) AS start_time, MAX(end_time) AS end_time
FROM Table1
GROUP BY id
) AS results INNER JOIN Table2 ON 
  results.job = Table2.job
  AND results.name = Table2.name
  AND (Table2.checkin_time BETWEEN results.start_time AND results.end_time OR
       Table2.checkin_time >= results.start_time AND results.end_time IS NULL);

将显示:

|  id |  name |  job    |      start_time      |     checkin_time    |  end_time    |       
| ----| ------| --------| ---------------------| --------------------|----------------|
| 111 |  John |  Janitor|  2016-08-20 00:01:00 | 2016-08-20 00:01:30 |2016-08-20 00:02:00 |
| 222 |  Sam  |  Valet  |  2016-08-20 00:03:00 | 2016-08-20 00:03:30 |2016-08-20 00:04:00 |

如何制定查询以便返回未成功/找不到的记录。例如。从表1开始,记录为:

|  Tim  |  Cashier|  2016-09-20 00:01:00 |

提前感谢您的帮助社区团队!

2 个答案:

答案 0 :(得分:1)

你可以做一个正确的加入并只过滤"没有匹配"使用空值:

SELECT table2.*
FROM (
    SELECT id,name,job, MIN(start_time) AS start_time, MAX(end_time) AS end_time
    FROM Table1
    GROUP BY id) AS results
RIGHT JOIN Table2 ON 
    results.job = Table2.job
    AND results.name = Table2.name
    AND (Table2.checkin_time BETWEEN results.start_time AND results.end_time OR
        Table2.checkin_time >= results.start_time AND results.end_time IS NULL)
WHERE results.id IS NULL

答案 1 :(得分:0)

您可以使用NOT-EXISTS子句来执行任务:在这里,您可以在table2中找到不在您的选择结果中的行。

SELECT
  name, job, checkin_time
FROM
  table2
WHERE NOT EXIST (
  SELECT *
  FROM
    v
  WHERE
    v.name = table2.name) 

结合在一起:

Create View v AS
(SELECT id, Table2.name, Table2.job, start_time, Table2.checkin_time, end_time FROM (
SELECT id,name,job, MIN(start_time) AS start_time, MAX(end_time) AS end_time
FROM Table1
GROUP BY id
) AS results INNER JOIN Table2 ON 
  results.job = Table2.job
  AND results.name = Table2.name
  AND (Table2.checkin_time BETWEEN results.start_time AND results.end_time OR
   Table2.checkin_time >= results.start_time AND results.end_time IS NULL));

SELECT
  name, job, checkin_time
FROM
  table2
WHERE NOT EXIST (
  SELECT *
  FROM
    v
  WHERE
    v.name = table2.name)