Reputation: 935
I want to see all users which following me or another user.
I have got used 3 tables
users
user_follow
images
I tried to get username with last image uploaded and also I need my and followers status to see if I already follow them or no.
My query is written on Mysql :
SELECT
u.id AS user_id,
u.username,
i.image,
t.id AS STATUS
FROM
users AS u
INNER JOIN (user_follow AS f)
ON (u.id = f.user_id)
LEFT OUTER JOIN images i
ON i.id =
(SELECT
b.id
FROM
images AS b
WHERE f.user_id = b.user_id
ORDER BY b.id DESC
LIMIT 1)
LEFT OUTER JOIN user_follow t
ON t.id =
(SELECT
m.id
FROM
user_follow m
WHERE user_id = 3
AND follow_id = u.id)
WHERE f.follow_id = 7
AND f.user_id NOT IN (7, 3)
GROUP BY f.user_id
My user id - 3; I watch users who are following user with id - 7
And output is :
Array
(
[0] => Array
(
[user_id] => 6
[username] => 6666
[image] => flw3utn9igiqh7dtt2o61ydf8_174.jpeg
[status] => 226
)
)
I think that my query is too heigh and I do not know how to simple check status and output 1 or 0 . Now I get a follow line id if "follow" and empty if no. Also I will be happy if you show me how to optimaize my query.
Upvotes: 0
Views: 150
Reputation: 1125
UVP - user who is viewing the page. FBV - User whose profile\list of follower is getting viewed. Last col of below query will give 0 if UVP is not following FBV else 1. It will be difficult to optimize the query 1) You want the row data in col (transpose){ first LOJ} 2) You have 2 tables where data might or might not be there {next 2 LOJ}
select *,(case when (uf3.id is not null) then 'follow' else null end) aa
from users u
left outer join
(Select * from
user_follow
where user_id = <FVP>
and follow_id =<UVP>) uf3 on uf3.user_id = u.id
left outer join
(select * from images where user_id = <FBV> ORDER BY id DESC
LIMIT 1) i
on i.user_id = u.id
left outer join
(Select *
from user_follow
where user_id =<FVP>
and follow_id !=<UVP>) uf on uf.user_id = u.id
where u.id =<FBV>;
Upvotes: 1