0

我有一张这样的桌子

id  type        type_id cust    ip_address      datetime
395 Category    5       0       119.63.196.29   2012-11-27 00:34:21
394 Cart        812     0       84.208.217.178  2012-11-27 00:31:48
393 Cart        812     0       84.208.217.178  2012-11-27 00:31:41
392 Cart        812     0       84.208.217.178  2012-11-27 00:31:35
391 Product     812     0       84.208.217.178  2012-11-27 00:31:34

我想选择 4 行,按 id desc 排序,它们具有不同的 type+type_id 数据。

因此查询的结果将删除 id 393 和 392,因为 type 和 type_id 组合已经在 id 394 中。

伪代码: select * from table where type and type_id is distinct from resultset, order by id desc limit 4

4

3 回答 3

3
select * from table
where id in 
(
  select min(id)
  from table 
  group by  type, type_id 
)
order by id desc
limit 4
于 2012-11-27T00:33:26.497 回答
0
SELECT *
  FROM AnonymousTable AS a1
  JOIN (SELECT type, type_id, MAX(id) AS id
          FROM AnonymousTable
         GROUP BY type, type_id
       ) AS a2
    ON a1.type = a2.type AND a1.type_id = a2.type_id AND a1.id = a2.id

不过,由于 ID 值可能是唯一的,您可以简化子查询和后续连接:

SELECT *
  FROM AnonymousTable AS a1
  JOIN (SELECT MAX(id) AS id
          FROM AnonymousTable
         GROUP BY type, type_id
       ) AS a2
    ON a1.id = a2.id

即使id不是唯一的(只要id,type和的组合type_id是唯一的),较长的形式也会产生正确的答案。

于 2012-11-27T00:39:22.190 回答
0

试试这个:

SELECT t1.* 
FROM table t1
INNER JOIN 
(
   SELECT MAX(id) maxid, type_id, type
   FROM table
   GROUP BY type_id, type
) t2 ON t1.id = t2.maxid AND t1.type = t2.type AND t1.type_id = t2.type_id
ORDER BY t1.id desc 
LMIT 4;

SQL 小提琴演示

于 2012-11-27T00:39:25.257 回答