使用GROUP BY连接两个表

时间:2015-04-18 12:55:41

标签: sql sql-server tsql

我有3张桌子:

enter image description here

这是我加入两个表(tbl_ads和tbl_inf_adstate)的查询的一部分:

       @state_id int=NULL
    AS  
    BEGIN  
          SET NOCOUNT ON;  

SELECT a.Id
      ,a.ad_title
      ,a.ad_brief  
      ,a.ad_pic    
    INTO #Results  
    FROM [tbl_ads] a JOIN tbl_inf_adstate b ON a.Id=b.ad_id 
    WHERE (b.state_id=@state_id OR @state_id IS NULL) 
    AND a.ad_is_accept=1 
    AND a.ad_is_show=1 
    AND a.ad_is_slide=0 
    order by a.ad_type ASC,NEWID()

@state_id参数是可选的。 我的问题是,结果会有多个重复的广告记录,但我只希望每个广告都有1条记录。

这是结果: enter image description here

4 个答案:

答案 0 :(得分:2)

只需将其与DISTINCT关键字区分开来:

SELECT DISTINCT a.Id
      ,a.ad_title
      ,a.ad_brief  
      ,a.ad_pic    
    INTO #Results  
    FROM [tbl_ads] a JOIN tbl_inf_adstate b ON a.Id=b.ad_id 
    WHERE (b.state_id=@state_id OR @state_id IS NULL) 
    AND a.ad_is_accept=1 
    AND a.ad_is_show=1 
    AND a.ad_is_slide=0

我已经删除了订购,因为这里没有意义。从临时表中选择时,不应该在插入该表时订购数据。

答案 1 :(得分:0)

尝试类似:

SELECT id, ad_title, ad_brief, ad_pic
FROM mytable
GROUP BY id, adTitle, adBrief, ad_pic

答案 2 :(得分:0)

Try this one :

SELECT  Id
      ,ad_title
      ,ad_brief  
      ,ad_pic    
INTO #Results
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY a.ID ORDER BY a.ID) AS rn, a.Id
      ,a.ad_title
      ,a.ad_brief  
      ,a.ad_pic
      ,a.ad_type    
    FROM [tbl_ads] a JOIN tbl_inf_adstate b ON a.Id=b.ad_id 
    WHERE (b.state_id=@state_id OR @state_id IS NULL) 
    AND a.ad_is_accept=1 
    AND a.ad_is_show=1 
    AND a.ad_is_slide=0 
)x
WHERE rn = 1
ORDER BY ad_type ASC,NEWID()

答案 3 :(得分:0)

删除订单,无用且浪费,将其添加到选择

SELECT a.Id
      ,a.ad_title
      ,a.ad_brief  
      ,a.ad_pic    
    INTO #Results  
    FROM [tbl_ads] a
    WHERE @state_id IS NULL
    OR exists ( SELECT 1 FROM tbl_inf_adstate b 
                WHERE a.Id=b.ad_id AND b.state_id=@state_id) 
    AND a.ad_is_accept=1 
    AND a.ad_is_show=1 
    AND a.ad_is_slide=0 

使用exists而不是连接,并且您没有重复项并且在两列上添加主键tbl_inf_adstate,因为您至少有2个相同的行