带有order by和limit的sql组查询

时间:2011-06-07 08:28:32

标签: mysql sql mysql-management

我的表格结构如下

| id   | cmp      | empid | empname | ttm  
+------+----------+-------+---------+------
|    2 | xyz      | 12    | swap    |    2 
|    2 | xyz      | 12    | sag     |    3
|    2 | xyz      | 14    | azr     |    1 
|    3 | pqr      | 2     | ron     |    2 
|    3 | pqr      | 22    | rah     |    1 
|    3 | pqr      | 32    | pra     |    5 

我已经完成了如下查询

(select * from test.companies where id = '2' order by ttm desc limit 2)
union
(select * from test.companies where id = '3' order by ttm desc limit 2);

它将输出如下

| id   | cmp      | empid | empname | ttm  
+------+----------+-------+---------+------
|    2 | wissen   | 12    | sag     |    3
|    2 | wissen   | 12    | swap    |    2 
|    3 | prolinkd | 32    | pra     |    5
|    3 | prolinkd | 2     | ron     |    2 

但我希望输出如下

| id   | cmp      | empid | empname | ttm  
+------+----------+-------+---------+------
|    3 | prolinkd | 32    | pra     |    5
|    3 | prolinkd | 2     | ron     |    2
|    2 | wissen   | 12    | sag     |    3 
|    2 | wissen   | 12    | swap    |    2 

表示哪个公司的最大ttm将首先显示

如果有人知道plz回复

由于

3 个答案:

答案 0 :(得分:2)

相当丑陋的外表和丑陋的声音,但它应该做你想要的。它为每个公司检索每个记录的“maxttm”,然后在排序中使用它来允许您根据公司的最高ttm为公司分配优先权。

SELECT * FROM (
    (SELECT *,
        (SELECT ttm FROM test.companies ic WHERE ic.id = oc.id ORDER BY ttm DESC LIMIT 1) AS maxttm
        FROM test.companies oc WHERE id = '2' ORDER BY ttm DESC LIMIT 2)
    UNION
    (SELECT *,
        (SELECT ttm FROM test.companies ic WHERE ic.id = oc.id ORDER BY ttm DESC LIMIT 1) AS maxttm
        FROM test.companies oc WHERE id = '3' ORDER BY ttm DESC LIMIT 2)
) AS myunion ORDER BY maxttm, id;

PS。感谢inti的查询我无耻地基于此。

答案 1 :(得分:1)

我认为这会奏效:

SELECT * FROM (

    (select * from test.companies where id = '2' order by ttm desc limit 2)
    union
    (select * from test.companies where id = '3' order by ttm desc limit 2)

) as myunion ORDER BY ttm;

得到你需要的东西,并通过ttm订购。

答案 2 :(得分:0)

select * 
from test.companies 
where id in ('2','3') 
and ttm > 1
order by ttm desc, id