0

DB Tables

What i need from the above tables are:

1.All user details corresponding to a id.

2.Number of post he had made.

3.Number of followers he has and number of people he is following (followid=user1.user2 [User1 is followin user2].

4.Let's say user1 is visting user2 profile, i need to find out if there exists followid corresponding to user1 and user2 i.e. user1.user2 in follow_detail.

I have achieved 1 and 2 by joining tables (post_detail and user_detail) and 3 by using a separate query (When-then in mysql). I was wondering if i can get all this in one SQL query.This is returned by profile API so hitting DB with multiple queries should not be good. If DB design is not good enough for this to get all above data in one query then i can change it.

1 Answer 1

1

By using subqueries you can combine the results into a single query. Whether that's more efficient than multiple simple queries - I'm not so sure. You need to test it.

select ud.*,
       (select count(*)
        from post_detail where post_detail.user_id=ud.user_id) as post_count,
       (select count(*)
        from follow_detail where follow_detail.following=ud.user_id) as follower_count,
       (select count(*)
        from follow_detail where follow_detail.follow=ud.user.id and follow_detail.following=...) as follower_user 
from user_detail ud
where ud.user_id=...

You need to provide the user ids in place of the .... I took quite a guess with the last subquery, since it was not clear what you would like to see there.

Sign up to request clarification or add additional context in comments.

2 Comments

From 4 what i want is:Suppose on facebook if i visits your profile, then i should know that if i am following you or not. Let's say my userid=123456 and your's is 234567 then i need to find if in my follow_detail table exits 123456.234567 (a boolean to notify if i am following you or not.)
Thanks to you.I did it (that 4th one).Thanks buddy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.