比较两个mysql表并显示更改

时间:2017-03-20 08:00:38

标签: php mysql

我有一个名为archive的表:

| staff_id |   longname  | username | projectNo |  title   | process | creation_time |
|    01    |   John Doe  |   John   |    1701   | project1 | ANM(ld) |  2017-01-16   |
|    02    | Aaron Jones |   Aaron  |    1701   | project1 | ANM(ch) |  2017-01-16   |
|    01    |   John Doe  |   John   |    1702   | project2 | CGI(ld) |  2017-01-16   |
|    01    |   John Doe  |   John   |    1701   | project1 | ANM(ld) |  2017-03-16   |
|    02    | Aaron Jones |   Aaron  |    1701   | project1 | BGD(ch) |  2017-03-16   |
|    01    |   John Doe  |   John   |    1702   | project2 | CGI(ld) |  2017-03-16   |  
|    03    | James Bond  |   James  |    1702   | project2 | BGD(ld) |  2017-03-16   |
|    03    | Peter Parker|   Peter  |    1702   | project2 | BAD(ld) |  2017-03-16   |

我想从表中获取带有最小日期的行:

SELECT staff_id, longname, username, title, process, creation_time FROM archived
WHERE creation_time IN (SELECT min(creation_time) FROM archived)

包含最新日期的行:

SELECT staff_id, longname, username, title, process, creation_time FROM archived
WHERE creation_time IN (SELECT max(creation_time) FROM archived)

然后我想比较收到的表,而只显示已更改和出现的行。所以从目前的表格我只想得到:

| staff_id |   longname  | username | projectNo |  title   | process | creation_time |
|    02    | Aaron Jones |   Aaron  |    1701   | project1 | BGD(ch) |  2017-03-16   |
|    03    | James Bond  |   James  |    1702   | project2 | BGD(ld) |  2017-03-16   |
|    03    | Peter Parker|   Peter  |    1702   | project2 | BAD(ld) |  2017-03-16   |

有没有办法在单个查询中执行此操作?如果不是如何在PHP中完成?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要执行right join

SELECT  t2.*
FROM    (
            SELECT  staff_id, longname, username, title, process, creation_time
            FROM    archived
            WHERE   creation_time IN (SELECT min(creation_time) FROM archived)
        ) t1
RIGHT JOIN (
            SELECT  staff_id, longname, username, title, process, creation_time
            FROM    archived
            WHERE   creation_time IN (SELECT max(creation_time) FROM 
        ) t2
ON      t1.staff_id = t2.staff_id AND
        t1.projectNo = t2.projectNo AND
        t1.process = t2.process
WHERE   t1.staff_id is null

右连接将保留第二个表格中的所有结果(具有最大值的表格),如果它们不匹配,则会在第一个表格的列上显示null个。这样,您可以对null的任何第一个表列进行过滤,以仅获取不匹配的行。

答案 1 :(得分:0)

您可以在最大结果表和最小结果表

之间使用左连接
select t1.* from ( 
  SELECT staff_id, longname, username, title, process, creation_time FROM archived
  WHERE creation_time IN (SELECT max(creation_time) FROM archived)
) t1
left join (
  SELECT staff_id, longname, username, title, process, creation_time FROM archived
  WHERE creation_time IN (SELECT min(creation_time) FROM archived)
) t2 on t1.staff_id = t2.staff_id and t1.creation_time = t2.creation_time
where t2.creation_time is null