如何在 sql 视图中排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2010276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort within a sql view
提问by Erwin
I've created a sql view and I need to sort the results of select by using the ORDER BY on 4 fields, but I'm getting message that ORDER BY cannot be used in views unless I use TOP. Can someone explain why TOP is needed, and does someone have a workaround for sorting in a sql view?
我创建了一个 sql 视图,我需要在 4 个字段上使用 ORDER BY 对 select 的结果进行排序,但是我收到消息,除非我使用 TOP,否则无法在视图中使用 ORDER BY。有人可以解释为什么需要 TOP,有人有在 sql 视图中排序的解决方法吗?
Thanks.
谢谢。
回答by Mladen Prajdic
you don't need to sort a view. a view is like a table so you sort it when you select from it:
您不需要对视图进行排序。视图就像一个表格,因此您可以在从中选择时对其进行排序:
select * from yourView order by yourColumns
回答by gbn
There is no guarantee the output of the view will be ordered
不能保证视图的输出会被排序
Only the outermost ORDER BY applies for result sets: not any inner ones. So only this ORDER BY can be guaranteed to work:
只有最外面的 ORDER BY 适用于结果集:不适用于任何内部的。所以只有这个 ORDER BY 才能保证工作:
SELECT col1, col2, FROm MyView ORDER BY col2
You can add it to views or derived tables and it forces "intermediate materialisation" because the results have to be ordered. However, for SQL Server 2005 and above, you have to use TOP 2000000000
not TOP 100 PERCENT
(except for that HF that Daniel Vassallo mentioned!)
您可以将它添加到视图或派生表中,它会强制“中间物化”,因为必须对结果进行排序。但是,对于 SQL Server 2005 及更高版本,您必须使用TOP 2000000000
not TOP 100 PERCENT
(Daniel Vassallo 提到的 HF 除外!)
Someone willuse your view with a different order to that internally at some point too.
在某些时候,有人也会以与内部不同的顺序使用您的视图。
回答by S?ng ??u
You can try:
你可以试试:
CREATE VIEW View_Products
AS
SELECT ProductID, ProductName, UnitPrice, CreateDate FROM Products
Order by CreateDate DESC
OFFSET 0 ROWS
回答by Ashutosh Misra
Would creating an index on the column with which you intend to sort the view help?
在您打算对视图进行排序的列上创建索引有帮助吗?
回答by RedFilter
If using SQL Server, you can do
如果使用 SQL Server,你可以这样做
select top 100 percent *
from MyTable
order by MyColumn
Of course you shouldn't use an * in your view, I just used it here for brevity.
当然,您不应该在您的视图中使用 *,我只是为了简洁起见在这里使用它。