我有两个表(为简洁起见,删除了多余的列)。
动作:
$(document).on('click', '#export-csv', function(){
$.ajax({
url: export_url,
type: 'post',
data:{ validations: validations },
dataType: 'json',
cache: false,
timeout: 1000000,
success: function (data) {
var resp = data.response;
console.log(resp);
},
error: function (error) {
console.log(error);
}
});
});
user_logs:
public function exportCsvAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
$input = $request->getPost();
$response = $this->getResponse();
$file = fopen('php://output', 'w');
foreach ($input['validations'] as $line) {
fputcsv($file, $line, chr(9), '"');
}
fclose($file);
header('Content-type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="validations-' . time() . '.csv"');
return $response->setContent(\Zend\Json\Json::encode(array('response' => true)));
}
return $this->getResponse()->setStatusCode(400);
}
我希望将这些表加入用户ID以及user_logs时间与操作时间之间的最小差异(例如,用户首先会在记录其操作之前登录users_logs表。
在同一用户的多个操作中准确无误的最佳方式是什么?
在此示例中,理想输出为
id user_id action created_at
1 1 open 2015-01-01 03:03:00
2 1 closed 2015-02-03 02:13:00
3 2 open 2015-02-04 03:23:00
答案 0 :(得分:0)
这可以通过内部联接实现,如下所示:
SELECT
user_logs.user_id,
actions.action,
user_logs.source,
FROM user_logs
INNER JOIN actions ON user_logs.user_id = actions.user_id
INNER JOIN
(
SELECT
MIN(TIMESTAMPDIFF(SECOND, user_logs.created_at, actions.created_at)) as minTime
FROM user_logs
INNER JOIN actions ON user_logs.user_id = actions.user_id
WHERE actions.created_at > user_logs.created_at
GROUP BY actions.id
) as minSelQ ON TIMESTAMPDIFF(SECOND, user_logs.created_at, actions.created_at) = minSelQ.minTime
GROUP BY actions.id