ORDER BY查询与WHERE NOT EXISTS

时间:2014-06-09 16:13:00

标签: sql sql-server-2008-r2

伙计们我试图显示表格中的所有记录,但前三条最新记录除外。我已经尝试过什么不存在,但我似乎无法让它工作。帮助将不胜感激。

EDITED: 查询:

SELECT  [Subject],
        IssueDate,
        (SELECT d.DepartName 
        FROM dbo.Department d 
        WHERE d.DepartmentID = n.DepartmentID) AS 'Department',
        Body, 
        NoticeImage, 
        Icon 
FROM dbo.Notice n 
WHERE NOT EXISTS (  SELECT TOP(3) [Subject],
                        IssueDate,
                        (SELECT d.DepartName 
                        FROM dbo.Department d 
                        WHERE d.DepartmentID = n.DepartmentID) AS 'Department', 
                        Body, 
                        NoticeImage, 
                        Icon 
                    FROM dbo.Notice n 
                    ORDER BY IssueDate DESC)
                    ORDER BY IssueDate DESC 

它确实被执行但是返回的行是0,即使db中有数据也是如此。如果重要的话,数据库中没有空值。

2 个答案:

答案 0 :(得分:1)

您的语法错误是order by子句必须在where子句之后。我也认为你采取了错误的做法。我会尝试这样的事情:

select myfields
from mytables
where SomeIdField not in 
(select top 3 SomeIdField
from mytables
where whatver
order by someField desc)
and other conditions
order by something

您可以填写详细信息。

答案 1 :(得分:0)

看来你只需要跳过前3行。

SELECT  [Subject],
        IssueDate,
        (SELECT d.DepartName 
        FROM dbo.Department d 
        WHERE d.DepartmentID = n.DepartmentID) AS 'Department',
        Body, 
        NoticeImage, 
        Icon 
FROM dbo.Notice n 
ORDER BY IssueDate DESC 
OFFSET 3;

使用JOIN而不是子查询

会更有效
SELECT  [Subject],
        n.IssueDate,
        d.DepartName AS 'Department',
        n.Body, 
        n.NoticeImage, 
        n.Icon 
FROM dbo.Notice n INNER JOIN dbo.Department d ON   d.DepartmentID = n.DepartmentID
ORDER BY IssueDate DESC 
OFFSET 3;

编辑:没有OFFSET子句的版本的脏技巧

select * from
    (SELECT  [Subject],
        n.IssueDate,
        d.DepartName AS 'Department',
        n.Body, 
        n.NoticeImage, 
        n.Icon,
        ROW_NUMBER() OVER (ORDER BY IssueDate DESC ) AS RowNum 
FROM dbo.Notice n INNER JOIN dbo.Department d ON   d.DepartmentID = n.DepartmentID
) subquery
where RowNum>3 
ORDER BY IssueDate DESC