简体   繁体   English

SQL:使用UNION,ORDER BY和LIMIT进行SELECT

[英]SQL: SELECT with UNION, ORDER BY and LIMIT

I'm getting Errors that ORDER by should come after UNION but i want these to queries ordered before combined to one and then limited to 10. 我得到的错误是ORDER by应该在UNION之后出现,但是我希望这些错误在订购之前被排序为一个然后限制为10。

SELECT * 
  FROM (SELECT time, x, y, z 
          FROM db 
         WHERE time >= now 
      ORDER by time, x
       UNION 
       SELECT time, x, y, z 
         FROM db 
        WHERE time < now 
     ORDER by time, x) 
LIMIT 10

I hope you understand, what I'm trying to do and can help me ;-) 我希望你明白,我正在努力做什么,可以帮助我;-)

if you have a very complex query in SQLite but need to use UNION with ordering, then you can try 如果您在SQLite中有一个非常复杂的查询但需要使用UNION进行排序,那么您可以尝试

select * from (
    select * from b ORDER BY date asc
    )
UNION
select * from (
    select * from b ORDER BY name desc
    )
UNION
select * from (
    select * from b ORDER BY gender asc
    )

An order by will affect the ENTIRE union. 订单将影响整个联盟。

Anyway, it looks like you want the rows nearest to now . 无论如何,看起来你想要最接近now的行。 You could try this: 你可以试试这个:

SELECT   time, x, y, z 
FROM     db 
ORDER BY ABS(time - now) ASC
LIMIT    10

That's not how it works, at least in MySQL (you didn't specify). 这不是它的工作原理,至少在MySQL中(你没有指定)。 The ORDER operation comes after the data is selected and all UNIONs, GROUP BYs, etc. have been performed. 在选择数据并执行了所有UNION,GROUP BY等之后进行ORDER操作。

See SQL Server: ORDER BY in subquery with UNION for a way around this. 有关此方法,请参阅带有UNION的子查询中的SQL Server:ORDER BY

In "standard" (for some definition of "standard") SQL; 在“标准”(对于某些“标准”的定义)SQL;

select top 10 *
from (       select time,x,y,z from db where time > now
       union select time,x,y,z from db where time < now
     ) t
order by t.time

How to limit the number of rows in the result set may vary between SQL implementations. 如何限制结果集中的行数可能因SQL实现而异。

Any easy solution I applied was as follows : 我应用的任何简单解决方案如下:

SELECT 
 name,
 TO_DATE(date1, 'DD-MON-YYYY HH:MI AM')
FROM TableX

UNION

SELECT
 name,
 TO_DATE(date2, 'DD-MON-YYYY HH:MI AM')
FROM TableY

ORDER BY 2 DESC;

This orders the results by the second (date) column. 这将按第二个(日期)列对结果进行排序。

If the date column is a string, you can apply the TO_DATE function as shown above, else it is not necessary. 如果date列是一个字符串,您可以应用如上所示的TO_DATE函数,否则没有必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM