删除自联接中的重复关系

时间:2018-01-18 05:50:02

标签: sql sql-server tsql

我需要自己加入一个表,其中id不应该相同,但市场应该是这样的  我找到了不同的市场,但是这样做我得到了重复;像1-3和3-1这样的关系我不需要两个条目  我只需要第一个1-3表中有数百万行,所以请帮我优化这个查询。

 declare @tbl table (id int   , market varchar(100))

 insert into @tbl (id,market)
 values(1,'abc'),(2,'xyz'),(3,'abc')

 select a.id , a.market , b.id ,b.market 
 from  @tbl a join  @tbl b 
 on a.id <> b.id 
 and a.market = b.market 

3 个答案:

答案 0 :(得分:1)

干净简单

select abc.id, abc.market , xyz.id , xyz.market
from  @tbl abc join  @tbl xyz
on abc.id <> xyz.id and abc.market = xyz.market and abc.id < xyz.id

Working SQL Fiddle

答案 1 :(得分:0)

试试这段代码:

<html>
<head>
    <script language='javascript'>
        function removeDivElements(){
            var x = document.getElementsByTagName("div");
            for (var i = 0; i < x.length; i++) {
                if( x[i].className == "mb-2" ){
                    x[i].outerHTML = "";
                    delete x[i];
                }
            }
        }
</script>
</head>
<body>
    <div id="contentatt">
        <div class="clearfix"></div>
        <div class="mb-2">
          <strong class="g2"><a class="tombol-nightmode">Night</a></strong> 
          <strong class="g2"><a class="tombol-birumode">Blue</a></strong> 
          <strong class="g2"><a class="tombol-hijaumode">Green</a></strong> 
          <strong class="g2"><a class="tombol-pinkmode">Pink</a></strong> 
          <strong class="g2"><a class="tombol-kuningmode">Yllw</a></strong> 
          <strong class="g2"><a class="tombol-mediummode"> - Med</a></strong> 
          <strong class="g2"><a class="tombol-fontmode"> - Big</a></strong>
        </div>
        <div class="clearfix"></div>
        <h1 class="title">I'm Really A Superstar - Chapter Prologue</h1>
        <div class="clear"></div>
    </div>
</body>
<script>
//call after page loaded
window.onload=removeDivElements;
</script>
</html>

希望这有帮助!

答案 2 :(得分:0)

尝试:它会将id视为字母数字。首先使用subquery返回不等于market的重复IDs集,然后按照您在示例中的操作加入

SELECT t.id, t.market, t1.id, t1.market
FROM(
    SELECT market, MIN(id) id
    FROM @tbl
    GROUP BY market HAVING COUNT(DISTINCT id) > 1) t
INNER JOIN @tbl t1 ON t1.market = t.market
    AND t1.id <> t.id