我不明白的另一个SQL语句

时间:2012-08-29 14:48:26

标签: sql

我知道我的问题的答案与排名有关,只是不知道该怎么做。我的陈述的目标是只获得5条记录,但优先考虑某个表中的记录而不是另一个表。

我有两个表:NewsNewsToLocation

让我们假装新闻表中有4个新闻项目,NewsToLocation中有3个符合我要求的新闻项目。由于我只能选择5,我想确保News表中的4获得首选项,然后仅从NewsToLocation表中选择1。我当前的查询正好相反,我无法弄清楚如何解决它。

这是整个查询。

SELECT 
newSpotlights.* 
FROM
(SELECT 
    TOP 5 n.news_id, 
    n.is_spotlight, 
    n.location_id, 
    n.news_title, 
    CAST(n.news_content AS varchar(200)) AS news_content, 
    n.writing_date,
    n.publication_date, 
    n.end_date, 
    n.alt_uri, 
    n.youtube_code, 
    n.icon_img_file, 
    n.banner_img_file
FROM 
    (SELECT 
        n.news_id
    FROM rcde_news n
    WHERE n.location_id = 4
    AND n.is_spotlight = 1 AND n.publication_date < GETDATE() AND n.end_date > GETDATE()
    AND n.status_id = 2 /*2 = Active rcde_ItemStatus*/
    UNION
    SELECT 
        n.news_id
    FROM rcde_newsToLocation ntl
    INNER JOIN rcde_news n ON ntl.news_id = n.news_id
    WHERE ntl.location_id = 4
    AND n.status_id = 2 /*2 = Active rcde_ItemStatus*/ 
    ) AS News
INNER JOIN rcde_news n ON news.news_id = n.news_id
WHERE n.is_spotlight = 1
AND n.publication_date < GETDATE()
AND n.end_date > GETDATE()
ORDER BY publication_date DESC
) AS newSpotlights

我觉得我应该能够通过对最内部查询进行排名来做一些顺序,但我不确定该怎么做。我有点理解排名但不知道如何在UNION语句中做到这一点。我可以做一些简单的事情,分别在联盟的不同部分选择1作为等级,2作为等级,然后按等级排序吗?

3 个答案:

答案 0 :(得分:1)

您可以将1作为排名,将2作为排名添加到查询的联合部分,然后按该排序。

SELECT 
    TOP 5 
    n.news_id, 
    n.is_spotlight, 
    n.location_id, 
    n.news_title, 
    CAST(n.news_content AS varchar(200)) AS news_content, 
    n.writing_date,
    n.publication_date, 
    n.end_date, 
    n.alt_uri, 
    n.youtube_code, 
    n.icon_img_file, 
    n.banner_img_file
FROM 
    (SELECT 
        1 as rank,
        n.news_id
    FROM rcde_news n
    WHERE n.location_id = 4
    AND n.is_spotlight = 1 AND n.publication_date < GETDATE() AND n.end_date > GETDATE()
    AND n.status_id = 2 /*2 = Active rcde_ItemStatus*/
    UNION
    SELECT 
        2 as rank,
        n.news_id
    FROM rcde_newsToLocation ntl
    INNER JOIN rcde_news n ON ntl.news_id = n.news_id
    WHERE ntl.location_id = 4
    AND n.status_id = 2 /*2 = Active rcde_ItemStatus*/ 
    ) AS News
INNER JOIN rcde_news n ON news.news_id = n.news_id
WHERE n.is_spotlight = 1
AND n.publication_date < GETDATE()
AND n.end_date > GETDATE()
ORDER BY rank DESC, publication_date DESC

答案 1 :(得分:0)

是的,你基本上都有你的等级想法:

select top 5 Column1, Column2
from (
    select top 5 Column1, Column2, 1 as Rank
    from News
    order by SomeColumn

    union all

    select top 5 Column1, Column2, 2 as Rank
    from NewsLocation
    order by SomeColumn
    ) x
order by Rank

答案 2 :(得分:0)

SELECT
    TOP 5 
    n.news_id
FROM 
    (SELECT 
        1 as ranking,
        n.news_id
    FROM rcde_news n
    WHERE blah blah
    UNION
    SELECT 
        2 as ranking,
        n.news_id
    FROM rcde_newsToLocation ntl
    WHERE blah blah

    ) AS News
ORDER BY publication_date DESC, Ranking