Mysql Sql命令分组前

时间:2016-03-19 21:19:31

标签: mysql sql

我的表格(用户):

id    sdate                  ip

1     2016-03-19 22:43:52    88.234.15.68
2     2016-03-19 22:43:58    88.234.15.68

我想简短然后分组。但我无法成功。我可以使用这个sql语句;

SELECT * 
FROM (SELECT * FROM users ORDER BY sdate DESC) as test 
GROUP BY test.ip 
ORDER BY sdate DESC

我得到以下输出:

SELECT * 
FROM (SELECT * FROM users ORDER BY sdate DESC) as test 
GROUP BY test.ip 
ORDER BY sdate DESC

id    sdate                  ip

1     2016-03-19 22:43:52    88.234.15.68

我想要这个输出

id    sdate                  ip

2     2016-03-19 22:43:58    88.234.15.68

2 个答案:

答案 0 :(得分:1)

如果我理解你想要实现的目标,你可以尝试这个查询:

SELECT      t1.*
    FROM    users t1
    JOIN    (
        SELECT      MAX(t.sdate) as sdate,
                    t.ip
            FROM    users t
        GROUP BY    t.ip
            ) t2
        ON  t2.sdate = t1.sdate
        AND t2.ip = t1.ip
  ORDER BY  t1.sdate DESC;

答案 1 :(得分:0)

您也可以使用JOIN的ID

SELECT u1.*, u2.*
FROM (
  SELECT max(id) AS id FROM `users` GROUP BY ip
  ) AS u1
LEFT JOIN `users` u2 ON u1.id  = u2.id;