加入最接近的先前时间戳

时间:2017-05-26 16:12:26

标签: mysql sql

我有一个用户网站互动表:

::: site_interactions :::
+-------+---------------------+
| user  | timestamp           |
+-------+---------------------+
| john  | 2017-01-01 15:00:00 |
+-------+---------------------+
| john  | 2017-01-01 15:30:00 |
+-------+---------------------+
| sarah | 2017-01-03 12:00:00 |
+-------+---------------------+

店内交易的辅助表:

::: store_transactions :::
+-------+---------------------+
| user  | timestamp           |
+-------+---------------------+
| john  | 2017-01-02 08:00:00 |
+-------+---------------------+
| sarah | 2017-01-02 09:00:00 |
+-------+---------------------+
| tim   | 2017-01-02 10:00:00 |
+-------+---------------------+

我想将网站互动加入到店内的东西中,但只返回:

a)最近的互动时间戳,但也

b)交互时间戳需要在事务时间戳

之前

所以在这个例子中,我最终得到:

+-------+---------------------+------------------------+
| user  | timestamp           | last_prior_interaction |
+-------+---------------------+------------------------+
| john  | 2017-01-02 08:00:00 | 2017-01-01 15:30:00    |
+-------+---------------------+------------------------+
| sarah | 2017-01-02 09:00:00 | NULL                   |
+-------+---------------------+------------------------+
| tim   | 2017-01-02 10:00:00 | NULL                   |
+-------+---------------------+------------------------+

我怀疑答案是使用HAVING和MIN,但是当我还需要强制执行先前的交互谓词时,我无法理解其工作原理。有什么提示吗?

3 个答案:

答案 0 :(得分:1)

http://rextester.com/WILC99478

SELECT
  st.username
, st.timestamp
, CASE WHEN si.timestamp < st.timestamp THEN si.timestamp ELSE NULL END 'last_prior_interaction'
FROM store_transactions st
LEFT JOIN (SELECT username
                , MAX(timestamp) timestamp
             FROM site_interactions                    
         GROUP BY username) si
               ON si.username = st.username

rextester不喜欢字段名称&#34; user&#34;,所以我将其替换为&#34;用户名&#34;。

完全披露:我觉得&#34; si.timestamp&lt; st.timestamp&#34; part可以在JOIN本身中处理,但这会拉出你要查找的数据。

答案 1 :(得分:1)

如果您在交易之前需要最新的时间戳,即使之后发生了新的交互,这里有一个正常工作的代码:

SELECT T.user, I.timestamp
FROM store_transactions T 
LEFT OUTER JOIN (
    SELECT I.user, MAX(I.timestamp) AS timestamp
    FROM site_interactions I 
    INNER JOIN store_transactions T ON I.user = T.user
    WHERE I.timestamp < T.timestamp
    GROUP BY I.user
) I ON I.user = T.user

答案 2 :(得分:0)

以下应该工作

Select st.user, st.timestamp, ut.timestamp  from   
    Store_transaction st left join site_transaction ut 
    on ut.user=st.user and ut.timestamp > st.timestamp;