优化一下这条sql

zzxap 2020-01-08 04:03:40
select 数据很慢 数据一千万以上

就是一个产品表和图片表
图片表的pid是产品表的id
id name
1 c
2 b

id pid imagename
1 1 aa
2 1 bb
3 2 cc
4 2 dd

要得到结果
id name imagename
1 c aa
2 b cc

这语句在mysql还是比较快的
在pgsql就很慢

select m.*,n.imageName from (
select * from Product where userid=119 order by id desc limit 100 offset 0

) m left join ( select pid,imageName from (select id,pid,imageName from images where userid=119 ) t where t.id=(select min(id) from (select id,pid,imageName from images where userid=119 ) u where pid=t.pid) ) n on m.id=n.pid order by m.id desc

...全文
310 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
roylam12345 2020-02-16
  • 打赏
  • 举报
回复
可以创建临时表,然后使用 delete from aa t1 where exists(select 1 from aa t2 where t1.pid=t2.pid and t1.id>t2.id) 这样能删除重复的 再进行关联匹配 或者不创建临时表,类似这种原理进行转一下,使用临时查询with
zzxap 2020-01-10
  • 打赏
  • 举报
回复
很慢很慢,索引建立了。 就是这一句超级慢 id pid imagename 1 1 aa 2 1 bb 3 2 cc 4 2 dd 重复数据只要最小id的

select  pid,imageName from (select id,pid,imageName from  images where userid=119  ) t 
where t.id=(select min(id) from (select id,pid,imageName from  images where userid=119 ) u  where pid=t.pid)
minsic78 2020-01-10
  • 打赏
  • 举报
回复
explain上执行计划,如果能执行出来,就用explain analyze

972

社区成员

发帖
与我相关
我的任务
社区描述
PostgreSQL相关内容讨论
sql数据库数据库架构 技术论坛(原bbs)
社区管理员
  • PostgreSQL社区
  • yang_z_1
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧