如何根据两个不同的列选择行?

时间:2012-11-27 00:31:08

标签: mysql

我有一张这样的表

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_id数据。

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

伪代码:从表中选择*,其中type和type_id与结果集不同,按id desc limit 4排序

3 个答案:

答案 0 :(得分:3)

select * from table
where id in 
(
  select min(id)
  from table 
  group by  type, type_id 
)
order by id desc
limit 4

答案 1 :(得分: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不唯一,长字体也会产生正确的答案(只要idtypetype_id的组合是唯一的)。< / p>

答案 2 :(得分: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 Fiddle Demo