简体   繁体   中英

how to combine these 2 sql queries in oracle?

I have these table, mega avatar is child of avatar which have mother and father.

avatar (avatarID,playerID,speciesName,charName,avatarDob,strength,gender,hoard)

megaAvatar(megaAvatarID,charName,megaAvatarDob,speciesName,magicPower,hoard,gender)

relationship(relationshipID,megaAvatarID,fatherAvaID,motherAvaID)

how to combine these 2 queries into one which can display father(avatar) and mother(avatar) details

    SELECT megaAvatar.charName, megaAvatar.speciesName, megaAvatar.magicPower,
            avatar.charName AS fatherName, avatar.speciesName AS fatherSpeciesName, 
species.speciesCost AS fatherSpeciesCost        
    FROM megaAvatar 
    INNER JOIN relationship ON megaAvatar.megaAvatarID = relationship.megaAvatarID
    INNER JOIN avatar ON relationship.fatherAvaID = avatar.avatarID
    INNER JOIN species ON avatar.speciesName = species.speciesName

    WHERE megaAvatar.hoard > 16;



SELECT megaAvatar.charName, megaAvatar.speciesName, megaAvatar.magicPower,
        avatar.charName AS motherName, avatar.speciesName AS motherSpeciesName, species.speciesCost AS motherSpeciesCost
FROM megaAvatar 
INNER JOIN relationship ON megaAvatar.megaAvatarID = relationship.megaAvatarID
INNER JOIN avatar ON relationship.motherAvaID = avatar.avatarID
INNER JOIN species ON avatar.speciesName = species.speciesName

WHERE megaAvatar.hoard > 16;

I have not tried it in Oracle SQL as I don't have it ... but it works in other DBMS ...

The idea is to join again on the same table and use different aliases ..

SELECT megaAvatar.charName, megaAvatar.speciesName, megaAvatar.magicPower,
        fatherAvatar.charName AS fatherName, fatherAvatar.speciesName AS fatherSpeciesName, 
        motherAvatar.charName AS motherName, motherAvatar.speciesName AS motherSpeciesName, 
        fatherSpecies.speciesCost AS fatherSpeciesCost, motherSpecies.speciesCost AS motherSpeciesCost
    FROM megaAvatar 
    INNER JOIN relationship ON megaAvatar.megaAvatarID = relationship.megaAvatarID

    INNER JOIN avatar as fatherAvatar ON relationship.fatherAvaID = fatherAvatar.avatarID
    INNER JOIN species as fatherSpecies ON fatherAvatar.speciesName = fatherSpecies.speciesName

    INNER JOIN avatar as motherAvatar ON relationship.motherAvaID = motherAvatar.avatarID
    INNER JOIN species as motherSpecies ON motherAvatar.speciesName = motherSpecies.speciesName

    WHERE megaAvatar.hoard > 16;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM