My table strucutre is as follows
| 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
I have done query on that like as follows
(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);
it will give output as follows
| 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
but i want output as follows
| 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
means which company has maximum ttm it will be shown first
If some one knows plz reply
Thanks
Rather ugly looking, and ugly sounding, but it should do what you want. It retrieves the "maxttm" for each company with each record, then uses that in sorting to allow you to assign priority to companies based on their highest 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. thanks to inti whose query I shamelessly based this on.
I think this will work:
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;
gets what you need, and orders it by ttm.
select *
from test.companies
where id in ('2','3')
and ttm > 1
order by ttm desc, id
精彩评论