[英]Need help optimize SQL query
I want to see all users which following me or another user. 我想查看所有关注我或其他用户的用户。
I have got used 3 tables 我已经用了3张桌子
users 使用者
user_follow 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 : 我的查询写在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; 我的用户ID-3; I watch users who are following user with id - 7 我看到关注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 . 我认为我的查询太高了,我不知道如何简单地检查状态并输出1或0。 Now I get a follow line id if "follow" and empty if no. 现在,如果有“ follow”,我将获得一条跟随线ID,如果没有,则为空。 Also I will be happy if you show me how to optimaize my query. 如果您向我展示如何优化查询,我也将很高兴。
UVP - user who is viewing the page. UVP-正在查看页面的用户。 FBV - User whose profile\\list of follower is getting viewed. FBV-正在查看其个人资料\\关注者列表的用户。 Last col of below query will give 0 if UVP is not following FBV else 1 . 如果UVP不跟随FBV,则下面查询的最后一个col将为0 ,否则为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} 优化查询将很困难1)您想要col中的行数据(转置){第一个LOJ} 2)您有2个表,数据可能存在或不存在{下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>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.