【问题标题】:Joining same table on itself自己加入同一张桌子
【发布时间】:2013-09-17 20:05:40
【问题描述】:

我的一个表存储来自用户浏览器的 UserAgent 以及与之关联的相应 UID,以及一些其他数据。每次用户登录时都会发生这种情况。因此每个用户都会有很多条目。我正在尝试查询此表以根据质量查找一些唯一用户。

例如,我试图只查找使用过 IE6 而没有其他浏览器的用户。到目前为止我能得到的最接近的是通过这种方法:

select distinct (U.UID) from TABLE1 tb1
inner join TABLE1 tb2 on tb1.UID = tb2.UID
where tb1.UserAgent like '%MSIE 6.%'
and tb2.UserAgent like '%MSIE 6.%'

这似乎返回了使用过 IE6 和任何其他浏览器的用户。我试图找到与此相反的情况。仅使用过 IE6 和 IE6 的用户。我也尝试了下面的一个,但也没有完全奏效,因为其中很大一部分用户有其他使用非 IE6 浏览器的条目。

select distinct (U.UID) from TABLE1 tb1
inner join TABLE1 tb2 on tb1.UID = tb2.UID
where tb1.UserAgent like '%MSIE 6.%'
and tb2.UserAgent not like '%MSIE 6.%'

我认为我在正确的轨道上,但可能会偏离这里。

TIA!

【问题讨论】:

    标签: sql sql-server-2000 user-agent


    【解决方案1】:

    选择用户代理like '%MSIE 6.%' 没有任何其他用户代理的用户。内部查询返回没有使用过'%MSIE 6.%'的用户

    select distinct tb1.UID from TABLE1 tb1
    where tb1.UserAgent like '%MSIE 6.%' and
          NOT EXISTS ( select tb2.UID from TABLE1 tb2
                       where tb1.UID = tb2.UID AND 
                             tb2.UserAgent not like '%MSIE 6.%' )
    

    您甚至可以使用NOT IN 代替NOT EXISTS,例如tb1.UID NOT IN (...)

    select distinct tb1.UID from TABLE1 tb1
    where tb1.UserAgent like '%MSIE 6.%' and
          tb1.UID NOT IN ( select tb2.UID from TABLE1 tb2
                           where tb2.UserAgent not like '%MSIE 6.%' )
    

    where 子句条件tb1.UserAgent like '%MSIE 6.%' and 也可以像NOT 一样被删除而没有任何副作用,并且内部查询确保用户的代理与%MSIE 6.% 匹配。

    【讨论】:

      【解决方案2】:
      select distinct (tb1.UID) from TABLE1  tb1
      where not exists (
                         select 1 
                         from TABLE1 
                         where UID = tb1.UID and UserAgent not like '%MSIE 6.%'
                       )
      

      【讨论】:

        【解决方案3】:

        无需加入,比 JOIN/NOT EXISTS 快得多:

        select UID 
        from TABLE1
        group by UID
        having max(case when UserAgent like '%MSIE 6.%' then 0 else 1 end) = 0
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-10-28
          • 2014-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多