在同一张桌子上的多个订单

时间:2014-04-24 13:31:57

标签: mysql

我们说我有3个简单的选择:

select * from `table` order by `id` desc limit 10

select * from `table` order by `date` desc limit 10

select * from `table` order by `name` desc limit 10

是否可以将这三者合并到一个查询中?

谢谢

3 个答案:

答案 0 :(得分:1)

您可以使用union all

(select * from `table` order by `id` desc limit 10)
union all
(select * from `table` order by `date` desc limit 10)
union all
(select * from `table` order by `name` desc limit 10);

答案 1 :(得分:0)

使用UNION

(select * from `table` order by `id` desc limit 10) T1
UNION
(select * from `table` order by `date` desc limit 10) T2
UNION
(select * from `table` order by `name` desc limit 10) T3

如果您还需要重复项,请将UNION替换为UNION ALL

答案 2 :(得分:0)

如果您想要一个结果集,只需使用以逗号分隔的列标识符列表order by

select * from `table` order by `id` desc, `date` desc, `name` desc limit 10

这将按id排序,如果ID相同,则按date排序,如果日期相同,请按name排序。

如果您需要三个结果集,请使用UNION ALL

(select * from `table` order by `id` desc limit 10)
union all
(select * from `table` order by `date` desc limit 10)
union all
(select * from `table` order by `name` desc limit 10)