简体   繁体   中英

Oracle sql query with multiple tables

As I mentioned in another question, I am working on small relational database queries for school. This query is to find male users with female friends. Here is the relevant structure of the database

Table: Users
Attributes: Id_pk, Name, Gender

Table: Friends
Attributes: Id1_pk (fk to users.id), Id2_pk (fk to users.id),Startdate

I am attempting to solve this query using this query:

select distinct id from friends, users, where users.id = id1 and users.gender = 'M'
intersect
select id from friends, users where users.id = id2 and users.gender = 'F'

So this is a valid search but no rows are selected though I certainly have friends between males and females in the database. I think I am running into a problem where i am checking the same users.gender twice, but I am not sure how to solve it. My thinking in constructing this query was to try to check the gender of the person in slots id1 and id2, making sure the id1 is a male and id2 is a female.

Thank you

Try this(assuming >=Oracle 9x):

 WITH FemalesQuery AS
(
    SELECT Id_pk
      FROM Users
     WHERE Gender = 'F'
), MalesQuery AS
(
    SELECT Id_pk
      FROM Users
     WHERE Gender = 'M'
)

SELECT Id2_pk
  FROM Friends
 WHERE Id1_pk IN (SELECT Id_pk FROM FemalesQuery)
   AND Id2_pk IN (SELECT Id_pk FROM MalesQuery)
 UNION
 SELECT Id1_pk
  FROM Friends
 WHERE Id2_pk IN (SELECT Id_pk FROM FemalesQuery)
   AND Id1_pk IN (SELECT Id_pk FROM MalesQuery)

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