获取与mysql表不同的结果是错误的结果

时间:2016-02-02 14:43:36

标签: mysql

我试图通过访问时间从mysql表顺序获取不同的记录,访问时间应该是以下查询的最新访问:

SELECT COUNT(*) as cookie_id, id, lead_id
FROM analytics where lead_id != 0 and user_id = 1
GROUP BY lead_id 
HAVING cookie_id > 1 order by visit_time desc

但是上面的查询我得错了结果。

**我的必需结果初始值:**

2054, 2016-02-02 14:19:40
2051, 2016-02-02 13:54:17
2055, 2016-02-02 12:22:16
2039, 2016-02-02 11:46:49

我的原始数据表屏幕附件。从下面的表格我试图获得过滤结果..

similar question

4 个答案:

答案 0 :(得分:2)

这就是你要找的东西

select lead_id, cookie_id, max(visit_time) as visit_time
from analytics
where lead_id != 0
and user_id = 1
group by lead_id, cookie_id
order by visit_time desc

确保您在lead_id,user_id和visit_time

上有索引

答案 1 :(得分:0)

你想要一个列的GROUPWISE MAXIMUM,手册中存在一个例子here

答案 2 :(得分:0)

这很简单。为了获得理想的结果( 上面提到的所需结果 )。您需要做的就是像这样使用GROUP BY

SELECT lead_id, visit_time
FROM analytics
GROUP BY lead_id

示例SQL:SQL FIDDLE

答案 3 :(得分:0)

这对我来说是解决方案:

SELECT count(lead_id) as lead_id_count, lead_id, cookie_id, max(id) as max_id,max(visit_time)
FROM analytics where user_id =1 and lead_id != 0 GROUP BY cookie_id,lead_id HAVING lead_id_count > 1 ORDER BY id DESC LIMIT 0 ,10