如何优化这条sql

写了一条sql,但是这条sql性能好差。

select *
  from (select t1.*,
               t2.*,
               t3.*,
               (select t4.b from t4 where t1.a = t4.a),
               '1' haha
          from t1, t2, t3
        
         where t1.c = t2.c
           and t1.c = t3.c
           and exists (select * from t3 where t3.c = t1.c)
           and exists (select * from t2 where t2.c = t1.c)
        
        union
        select t1.*,
               t2.*,
               t3.*,
               (select t4.b from t4 where t1.a = t4.a),
               '2' haha
          from t1, t2, t3
        
         where t1.c = t2.c
           and t1.c = t3.c
           and not exists (select * from t3 where t3.c = t1.c)
           and exists (select * from t2 where t2.c = t1.c)
        
        union
        select t1.*,
               t2.*,
               t3.*,
               (select t4.b from t4 where t1.a = t4.a),
               '3' haha
          from t1, t2, t3
        
         where t1.c = t2.c
           and t1.c = t3.c
           and exists (select * from t3 where t3.c = t1.c)
           and not exists (select * from t2 where t2.c = t1.c))t

请教,这个sql还有更好的写法吗?

阅读 1.7k
1 个回答

看不懂你要查什么。多表查询 用关联查询,inner join left join 什么的。如果想判断某表有没有值,可以用这个表 left join 主表,如果关联不到就是没有

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进