如何从彼此内部连接的表中选择不同的记录

时间:2013-11-29 11:42:09

标签: sql-server sql-server-2008

我有3张桌子

News        (News_ID,Title,Article,Attatchment,Publish_Status,Sort_Order,Date,Read_Status)
Category     (Category_ID,Category_Name,Parent)
News_Category(ID,News_ID,Category_ID)

我想从表新闻中选择前4条记录,其中News_Category表中的Category_ID为12,并且其类别表中的Parent为12。 我使用了以下查询: -

 SELECT  DISTINCT 
        News.News_ID, News.Title, News.Article, News.Attatchment, News.Publish_Status, News.Sort_Order, News.Read_Status, News.[Date]
        ,News_Category.ID
        ,Category.Category_Name 
FROM News 
INNER JOIN News_Category ON News_Category.News_ID = News.News_ID 
INNER JOIN Category ON News_Category.Category = Category.Category_ID  
WHERE News_Category.Category in 
            (   select Category_ID 
                from Category 
                where Category_ID=12 
            union 
                select Category_ID 
                from Category 
                where Parent=12 )
ORDER BY News.News_ID DESC

但是当我在父类= 12的两个类别中插入单个新闻时,它显示重复数据。请帮助我。

1 个答案:

答案 0 :(得分:1)

离开News_Category.ID我应该解决它。

SELECT  DISTINCT 
        News.News_ID, News.Title, News.Article, News.Attatchment, News.Publish_Status, News.Sort_Order, News.Read_Status, News.[Date]
        ,Category.Category_Name 
FROM News 
INNER JOIN News_Category ON News_Category.News_ID = News.News_ID 
INNER JOIN Category ON News_Category.Category = Category.Category_ID  
WHERE News_Category.Category in 
            (   select Category_ID 
                from Category 
                where Category_ID=12 
                or Parent=12 )
ORDER BY News.News_ID DESC