Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are two selects needed?

Tags:

sql

mysql

I have a table:

Visit (FromId, ToId, VisitTime)

where FromId and ToId are FKs to table

UserProfile (uid, name, age ...)

As a user with my UID I want to select all profiles I have visited or who visited me in one result set ordered by VisitTime and with the indication of the "direction of the visit".

Is it possible to do it using only one MySQL query?

like image 210
Petr B Avatar asked Jul 29 '26 21:07

Petr B


1 Answers

SELECT  CASE WHEN a.FromID = 'yourIDHere' 
                THEN c.Name
                ELSE b.Name
        END Name,
        CASE WHEN a.FromID = 'yourIDHere' 
                THEN c.Age
                ELSE b.Age
        END Age,
        a.VisitTime,
        CASE WHEN a.FromID = 'yourIDHere' 
                THEN 'You'
                ELSE 'Friend'
        END DirectionOfVisit
FROM    Visit a
        INNER JOIN UserProfile b
            ON a.FromID = b.Uid
        INNER JOIN UserProfile c
            ON a.ToID = c.Uid
WHERE   'yourIDHere' IN (a.FromID, a.ToID)
ORDER   BY a.VisitTime

Brief Explanation:

The query will display the name of your friend you visited or who have visited you and will also display the direction of the visit. When it displays You, it means that you have visited your friend's profile, otherwise it will display Friend if the friend have visited you.

  • SQLFiddle Demo
like image 185
John Woo Avatar answered Jul 31 '26 09:07

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!