简体   繁体   中英

SQL Union or other table join

I'm having trouble wrapping my head around an SQL query, trying to figure out something.

Just quickly, here is my (simple) table: It's a representation of friends added in a social network site. I have to use the table format like this, user1 and user2 are both primary keys.

          User1       |       User2
    --------------------------------------
      foo@a.com       |   things@stuff.com
      foo@a.com       |   lala@hi.com
      things@stuff.com|   lol@k.com
      lol@k.com       |   foo@a.com
      foo@a.com       |   lol@k.com

What I need to do is write a SELECT statement that will return all unique users that are friends with foo@a.com for example.

SELECT User2
FROM members 
WHERE User1 = 'things@stuff.com'

Would return lol@k.com and not foo@a.com, even though I need it to return the latter.

SELECT *
FROM members
WHERE User1 = 'foo@a.com'
OR User2 = 'foo@a.com'

Would return an error I think? Something with selecting multiple columns probably.

So I figure a union join or some other join is necessary (union so no duplicates?) but I'm really not sure how to go about doing it.

I'm trying to implement this in PHP, so even if the last query I wrote worked, I'm not sure how to echo User1 or User2 depending on which it returned/which one I needed if that makes sense.

Using a UNION (for performance) :-

SELECT User2
FROM members
WHERE User1 = 'foo@a.com'
UNION
SELECT User1
FROM members
WHERE User2 = 'foo@a.com'

Use an alias name for the column

SELECT User2 AS friend
FROM members 
WHERE User1 = 'things@stuff.com'
UNION
SELECT User1 AS friend
FROM members 
WHERE User2 = 'things@stuff.com'

Now you can echo friend .

HTH

It all depends on how you define the relationship between the two users.

For example, you have a table entry where User1 = 'foo@a.com' and User2='mumu@f.com'. What does it mean? Does it mean that user foo became friends with mumu? Does it matter the direction of the 'friendship'?

If the answer is no an you simply want to fetch all rows where either user is foo, then your query

    SELECT *
FROM members
WHERE User1 = 'foo@a.com'
OR User2 = 'foo@a.com'

is correct.

However, to fetch the data you need to explore both columns for results.

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