我有一个很大的选择,当我使用解释它显示:
我需要使用force index
在pp表上使用(user)
作为索引(键)。
强制索引后,它将删除pp2
表中的用户(密钥)。所以我也需要在(user)
上使用强制索引pp2
。
强制在pp
和pp2
上建立索引后,表格p
将自动使用primary
作为索引,并且一切正常。
我的问题是,问题是什么?为什么mysql没有在pp表中使用possible_keys user
作为键?
为什么在我强制pp
使用user
密钥后,它会弄乱pp2
上的密钥?在它上面添加key = null。
为什么在强制pp
和pp2
使用用户作为键之后,表p将使用primary作为键并且所有都可以正常工作?
SQL:
select c.nome, p.foto, c.user, p.user, p.id, p.data, p.titulo, p.youtube, pp.foto, count(DISTINCT likes.user) as likes_count, count(distinct comentarios.id) as comentarios_count, count(DISTINCT l2.user) as count2,
linked.id as shared_id, linked.titulo as shared_titulo, linked.user as shared_user_id, c2.user as shared_nick, linked.foto as shared_foto, pp2.foto as shared_perfil,
count(DISTINCT share_count.id) as shares_count
from posts p
join cadastro c on p.user=c.id
left join profile_picture pp force index (user) on p.user = pp.user
left join likes on likes.post = p.id
left join comentarios on comentarios.foto = p.id and comentarios.delete = 0
left join likes l2 on l2.post = p.id and l2.user = 1
left join posts linked on linked.id = p.post_share
left join cadastro c2 on linked.user=c2.id
left join profile_picture pp2 force index (user) on linked.user = pp2.user
left join posts share_count on share_count.post_share = p.id and share_count.delete=0
where (p.user in (select following from following where user =1 and block=0) or p.user=1) and p.delete=0
group by p.id
order by p.id desc limit 15
个人资料图片:
CREATE TABLE `profile_picture` (
`user` int(11) UNSIGNED NOT NULL,
`foto` varchar(400) NOT NULL,
UNIQUE KEY `user` (`user`)
) ENGINE=InnoDB ;
感谢。
答案 0 :(得分:1)
为了提高性能,你也可以避免使用IN子句并使用内部连接,例如:(我希望)
select c.nome, p.foto, c.user, p.user, p.id, p.data, p.titulo, p.youtube, pp.foto, count(DISTINCT likes.user) as likes_count, count(distinct comentarios.id) as comentarios_count, count(DISTINCT l2.user) as count2,
linked.id as shared_id, linked.titulo as shared_titulo, linked.user as shared_user_id, c2.user as shared_nick, linked.foto as shared_foto, pp2.foto as shared_perfil,
count(DISTINCT share_count.id) as shares_count
from posts p
join cadastro c on p.user=c.id
left join profile_picture pp force index (user) on p.user = pp.user
left join likes on likes.post = p.id
left join comentarios on comentarios.foto = p.id and comentarios.delete = 0
left join likes l2 on l2.post = p.id and l2.user = 1
left join posts linked on linked.id = p.post_share
left join cadastro c2 on linked.user=c2.id
left join profile_picture pp2 force index (user) on linked.user = pp2.user
left join posts share_count on share_count.post_share = p.id and share_count.delete=0
inner join following f on (f.following = p.user and f.user=1 and f.block = 0 and p.delete=0)
OR ( p.user=1 and p.delete =0)
group by p.id
order by p.id desc limit 15
并查看您的pp表,其中您在用户中有一个唯一索引,您可以尝试将其更改为创建中的pk条件
CREATE TABLE `profile_picture` (
`user` int(11) UNSIGNED NOT NULL,
`foto` varchar(400) NOT NULL,
PRIMARY KEY (`user`)
) ENGINE=InnoDB ;