MySQL UNION和ORDER - 单个表上的多个选择查询

时间:2014-12-10 14:40:27

标签: mysql

我试图从一张桌子中选择最多250行。首先,我想选择列ALL的{​​{1}}行,然后选择locked='1'行,列X按列locked = '0'排序(时间戳)

X是来自firest查询的250 - num行。

我试过了:

since

但是我没有通过第二次查询得到正确的值(不是select * from ( select * from aktivni as a1 where locked = '1' union select * from aktivni as a2 where locked = '0' ) as tb1 limit 250 订购的)。

如果我这样做:

since

所有订单都由select * from ( select * from aktivni as a1 where locked = '1' union select * from aktivni as a2 where locked = '0' ORDER BY since DESC ) as tb1 limit 250 排序,而且我没有获得sinceALL设置为1的值。

工会是正确的方法还是我可以做别的事情?

解决方法是在php中编写代码来执行此操作。首先,我会选择所有: locked

比我计算行数和第二个查询得到剩余的行 SELECT * FROM table WHERE locked = '1'但我想避免这种情况。

1 个答案:

答案 0 :(得分:2)

无需union - 您只需在order by limit中使用条件:

select locked, since
from aktivni cross
order by locked = '1' desc, since desc
limit 250