簡體   English   中英

SQL幫助內連接左連接

[英]SQL Help Inner JOIN LEFT JOIN

我的查詢是:

SELECT Pics.ID, Pics.ProfileID, Pics.Position, Rate.ID as RateID, Rate.Rating, Rate.ProfileID, Gender
FROM Pics
    INNER JOIN Profiles ON Pics.ProfileID = Profiles.ID
    LEFT JOIN Rate ON Pics.ID = Rate.PicID
WHERE Gender = 'female'
ORDER BY Pics.ID

結果是:

ID ProfileID Position RateID Rating ProfileID Gender
23 24        1        59     9      42        female
24 24        2        33     8      32        female
23 24        1        53     3      40        female
26 24        4        31     8      32        female
30 25        4        30     8      32        female
24 24        2        58     4      42        female

現在,我要執行另一個查詢,即:如果Rate.ProfileID = 32,則刪除任何包含相同Pics.ID的行。

所以留下:

ID ProfileID Position RateID Rating ProfileID Gender
23 24        1        59     9      42        female
23 24        1        53     3      40        female

並刪除所有重復的Pics.ID,因此它們都是23,因此只保留了上述之一:

23 24 1 59 9 42母頭或23 24 1 53 3 40母頭

您可能應該擺脫“神奇數字”,例如32。也就是說,我認為這將為您提供所需的東西。

SELECT
    P.ID,
    P.ProfileID,
    P.Position,
    R.ID as RateID,
    R.Rating,
    R.ProfileID,
    PR.Gender
FROM
    Pics P
INNER JOIN Profiles PR ON PR.ID = P.ProfileID
LEFT JOIN Rate R ON R.PicID = P.ID
WHERE
    PR.Gender = 'female' AND
    NOT EXISTS (
        SELECT *
        FROM Pics P2
        INNER JOIN Profiles PR2 ON PR2.ID = P2.ProfileID
        INNER JOIN Rate R2 ON R2.PicID = P2.ID AND R2.ProfileID = 32
        WHERE
            P2.ID = P.ID
    )
ORDER BY
    P.ID

@Shadow因為第二行包含Rate.ProfileID = 32,並且該Pic.ID = 24,所以它必須刪除所有Pic.ID = 24,這也刪除了底行。

SELECT Pics.ID, Pics.ProfileID, Pics.Position, Rate.ID as RateID, Rate.Rating, Rate.ProfileID, Gender
FROM Pics
INNER JOIN Profiles ON Pics.ProfileID = Profiles.ID
LEFT JOIN Rate ON Pics.ID = Rate.PicID
WHERE Gender = 'female' AND Pics.ID NOT IN (
    SELECT Pics.ID 
    FROM Pics
    INNER JOIN Profiles ON Pics.ProfileID = Profiles.ID
    LEFT JOIN Rate ON Pics.ID = Rate.PicID
    WHERE Gender = 'female' AND Rate.ProfileID = 32)

ORDER BY Pics.ID

嘗試這個:

SELECT Pics.ID, Pics.ProfileID, Pics.Position, Rate.ID as RateID, 
       Rate.Rating, Rate.ProfileID, Gender
FROM Pics
INNER JOIN Profiles ON Pics.ProfileID = Profiles.ID
LEFT JOIN Rate ON Pics.ID = Rate.PicID
LEFT JOIN Rate AS r 
   ON Rate.ProfileID = r.ProfileID AND Rate.ID > r.ID
WHERE Gender = 'female' AND (Pics.ProfileID <> 32) AND (r.ID IS NULL)
ORDER BY Pics.ID

最后一個LEFT JOIN操作使用ON子句中的此謂詞幫助識別重復項:

Rate.ProfileID = r.ProfileID

如果存在此類重復項(如Rate.ProfileID = 42的情況),則由於以下條件,僅返回具有最大 Rate.ID

Rate.ID > r.ID (`ON` clause)

(r.ID IS NULL) (`WHERE` clause)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM