[英]Need help optimize SQL query
我想查看所有关注我或其他用户的用户。
我已经用了3张桌子
使用者
user_follow
图片
我尝试获取上载有上一张图片的用户名,并且我还需要我和关注者的状态以查看是否已经关注他们。
我的查询写在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
我的用户ID-3; 我看到关注ID为7的用户的用户
输出为:
Array
(
[0] => Array
(
[user_id] => 6
[username] => 6666
[image] => flw3utn9igiqh7dtt2o61ydf8_174.jpeg
[status] => 226
)
)
我认为我的查询太高了,我不知道如何简单地检查状态并输出1或0。 现在,如果有“ follow”,我将获得一条跟随线ID,如果没有,则为空。 如果您向我展示如何优化查询,我也将很高兴。
UVP-正在查看页面的用户。 FBV-正在查看其个人资料\\关注者列表的用户。 如果UVP不跟随FBV,则下面查询的最后一个col将为0 ,否则为1 。 优化查询将很困难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.