2016-12-04 58 views
1

我有兩個表:提取物倒重複值的sql

  • Likes(IDPerfilA,IDPerfilB,數據)
  • Amizade(IDPerfilA,IDPerfilB,數據)

*友誼大馬路=朋友在英語。

我的表喜歡上傳了許多喜歡,約束不允許IDPerfilA喜歡相同的IDperfilB(EX:ID 4的用戶不喜歡ID 4的用戶)。

現在,我要上傳我的朋友與以下ID的表:

如果,存在於喜歡錶用戶4個喜好8,8喜歡4,那麼這是一個友好,讓他們去和朋友從喜歡中刪除。

我試過以下,但我的朋友們表作爲反轉重複值(例如:4是朋友8,8與4個朋友)

INSERT INTO AMIZADE (IDPERFILA, 
        IDPERFILB, 
        DATA) 
SELECT a.IDPERFILA, a.IDPERFILB, a.DATA 
FROM LIKES as a, LIKES as b 
WHERE (a.IDPERFILB = b.IDPERFILA AND a.IDPERFILA = b.IDPERFILB) 

我用下面的代碼來刪除好友喜歡:

DELETE LIKES 
from 
LIKES as l inner join amizade as a 
on a.IDPERFILA = l.IDPERFILA 
    and a.IDPERFILB = l.IDPERFILB 
    and a.DATA = l.DATA 

如果有人能幫助我,這將是偉大的!提前致謝。

回答

0

這項工作?

INSERT INTO AMIZADE (IDPERFILA, 
        IDPERFILB, 
        DATA) 
SELECT DISTINCT CASE WHEN (a.IDPERFILA > a.IDPERFILB) THEN a.IDPERFILA 
      ELSE a.IDPERFILB 
      END 
     , CASE WHEN (a.IDPERFILA <= a.IDPERFILB) THEN a.IDPERFILB 
      ELSE a.IDPERFILA 
      END 
     , a.DATA 
FROM LIKES as a, LIKES as b 
WHERE (a.IDPERFILB = b.IDPERFILA AND a.IDPERFILA = b.IDPERFILB) 
0

我猜你希望這對(4,8)只出現在朋友表中一次。我會去:

INSERT INTO AMIZADE (IDPERFILA, IDPERFILB, DATA) 
    SELECT l.IDPERFILA, l.IDPERFILB, l.DATA 
    FROM LIKES l 
    WHERE EXISTS (SELECT 1 
        FROM LIKES l2 
        WHERE l2.IDPERFILA = l.IDPERFILB AND l2.IDPERFILB = l.IDPERFILA 
       ) AND 
      l.IDPERFILA < l2.IDPERFILB; 

如果你想在amizade表中的兩個對,你可以刪除最後一個條件。

您可能還想強制給定的對只能進入amizade表中一次。如果是這樣,你可以用唯一索引和檢查約束來做到這一點:

alter table amizade constraint chk_amizade_idperfilA_idperfilB 
    check (idperfilA < idperfilB); 

alter table amizade constraint unq_amizade_idperfilA_idperfilB 
    unique (idperfilA, idperilB); 

這兩個檢查將確保友誼對是唯一的。注意:您確實需要注意如何插入數據。

0
INSERT INTO AMIZADE (IDPERFILA, 
       IDPERFILB, 
       DATA) 
SELECT a.IDPERFILA, a.IDPERFILB, a.DATA 
FROM LIKES as a, LIKES as b 
WHERE (a.IDPERFILB = b.IDPERFILA AND a.IDPERFILA = b.IDPERFILB) 
**and (a.IDPrfila > a.IDPerfilb)** 

只是添加聲明inbetween德**和工作。謝謝你的提示