3

这是数据库表

╔════╦═════════════╦══════════════════╦═══════╗
║ id ║ customer_id ║    last_seen     ║ param ║
╠════╬═════════════╬══════════════════╬═══════╣
║  1 ║       12345 ║ 2012-08-01 12:00 ║     1 ║
║  2 ║       22345 ║ 2012-08-01 12:00 ║     1 ║
║  3 ║       32345 ║ 2012-08-01 12:00 ║     1 ║
║  4 ║       42345 ║ 2012-08-01 12:00 ║     1 ║
║  5 ║       52345 ║ 2012-08-01 12:00 ║     1 ║
║  6 ║       12345 ║ 2012-09-01 12:00 ║     2 ║
║  7 ║       12345 ║ 2012-10-01 12:00 ║     3 ║
╚════╩═════════════╩══════════════════╩═══════╝

其中id是 AUTO INCREMENT 主键。

我想要实现的是获取每个customer_id. 预期结果 :

╔════╦═════════════╦══════════════════╦═══════╗
║ id ║ customer_id ║    last_seen     ║ param ║
╠════╬═════════════╬══════════════════╬═══════╣
║  2 ║       22345 ║ 2012-08-01 12:00 ║     1 ║
║  3 ║       32345 ║ 2012-08-01 12:00 ║     1 ║
║  4 ║       42345 ║ 2012-08-01 12:00 ║     1 ║
║  5 ║       52345 ║ 2012-08-01 12:00 ║     1 ║
║  7 ║       12345 ║ 2012-10-01 12:00 ║     3 ║
╚════╩═════════════╩══════════════════╩═══════╝

我试过这个 SQL,但它返回不正确的结果:

SELECT customer_id, param, last_seen 
FROM `my_table` 
GROUP BY customer_id 
ORDER BY last_seen DESC 

我在这里想念什么?

更新:表结构(输出DESC my_table

+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| customer_id  | varchar(8)   | NO   |     | NULL    |                |
| last_seen    | datetime     | NO   |     | NULL    |                |
| param        | int(11)      | NO   |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+
4

2 回答 2

7

子查询背后的想法是它分别获取last_seen每个Customer_ID. 如果必须满足条件,则子查询的结果将与原始表连接:CustomerID日期必须相互匹配。

SELECT  a.*
FROM    Customer a
        INNER JOIN
        (
            SELECT Customer_ID, MAX(last_seen) maxDate
            FROM Customer
            GROUP BY Customer_ID
        ) b ON a.Customer_ID = b.Customer_ID AND
                a.last_seen = b.maxDate
ORDER BY a.ID

追问:能否请您检查一下last_seen记录id的值6是否正确?

于 2012-12-14T08:32:36.350 回答
0

这是一个SQLFiddle 演示

在 MySQL 中,您可以这样做:

select ID,CUSTOMER_ID,LAST_SEEN,PARAM from
(
   select t.*,
       if(@i=customer_id,0,1) isLast,
       @i:=customer_id 
       from `my_table` t,(select @i:=0) t1 
   order by customer_id,last_seen desc
) t2 where isLAst=1
于 2012-12-14T08:45:15.737 回答