从DB中选择项目与另一个表中的最新日期进行比较

时间:2016-09-13 13:48:06

标签: php mysql

我想从userLogTable中选择记录比activityTable中最新匹配项更新的所有项目。我想在一个查询中执行此操作。

目前,我从一个表中进行选择,然后在匹配另一个表时循环显示结果。

SELECT COUNT(*) AS Visits, userLogTable.* FROM userLogTable GROUP BY Name, Date

userLogTable
Name   | Surname | Date
-----------------------------
Dave   | Smith   | 2016-06-01
Jane   | Doe     | 2016-06-01
Dave   | Smith   | 2016-06-02
Dave   | Smith   | 2016-06-01
Jane   | Doe     | 2016-06-03
Peter  | Bloggs  | 2016-06-03
Steve  | Foo     | 2016-06-01
Steve  | Foo     | 2016-06-01
// many more rows

// above SQL returns the following result as expected/needed
Name   | Surname |  Date       | Visits
----------------------------------------
Dave   | Smith   |  2016-06-01 | 2
Jane   | Doe     |  2016-06-01 | 1
Dave   | Smith   |  2016-06-02 | 1
Jane   | Doe     |  2016-06-03 | 1
Peter  | Bloggs  |  2016-06-03 | 1
Steve  | Foo     |  2016-06-01 | 2

activityTable
Name   | Surname | Date
------------------------------
Dave   | Smith   | 2016-06-03
Dave   | Smith   | 2016-06-03
Dave   | Smith   | 2016-06-03
Dave   | Smith   | 2016-06-02
Dave   | Smith   | 2016-06-02
Dave   | Smith   | 2016-06-02
Dave   | Smith   | 2016-06-01
Dave   | Smith   | 2016-05-29
Dave   | Smith   | 2016-05-29
// many more rows

QUERY:

foreach($userLogTableResult as $key => $val) {
    // db function
    SELECT Date 
    FROM activityTable  
    WHERE Date > $latestDateFromUserLogTable 
      AND NAME = $val['Name'] 
      AND Surname = $val['Surname'] 
    ORDER BY Date DESC LIMIT 1 
    // if there is a result then unset this item as it's older than the latest activity
}

非常感谢任何帮助。

此示例已广泛简化了上述代码。我正在构建SQL并将其解析为自定义PDO函数。所有值都会相应地进行转义和消毒。

1 个答案:

答案 0 :(得分:0)

我认为这可以满足您的需求:

(0, 2, 3, 5, 6, 7, 8, 9)
(0, 4, 9, 25, 36, 49, 64, 81)