[英]SELECT items from DB comparing to latest date in another table
我想從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
查詢:
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函數。 所有值都將被轉義並進行相應的清理。
我認為這可以滿足您的需求:
select ult.*
from userLogTable ult
where ult.date > (select max(a.date)
from activityTable a
where a.name = ult.name and a.surname = ult.surname
) ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.