使用多个表进行MySQL连接,避免使用子查询方法
P粉442576165
P粉442576165 2023-09-07 17:38:48
0
2
453

我在fiddle中的查询如下。

select * from notification where status = 0 and (
 notif_id in (select notif_id from notif_user where user_id = 1) OR 
 notif_id in (select notif_id from notif_group where group_id = 1))

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=cad284e77218eb37461e60b6308bf85f

查询按预期工作。但是,查询是否会有任何性能问题。是否可以将内部查询转换为连接?

P粉442576165
P粉442576165

全部回复(2)
P粉567281015

您的子查询不是依赖子查询,而是独立的。也就是说,它们不引用您的notification表中的列,而只引用它们自己表中的列。

所以这里没有性能问题。

P粉576184933

您可以将子查询表示为联合查询,并比较执行计划统计信息。查看fiddle中的输出,union似乎执行稍微更好。

select * 
from notification 
where status = 0 and (
 notif_id in (
    select notif_id from notif_user where user_id = 1 union all
    select notif_id from notif_group where group_id = 1
  )
);

另一种表达方式是使用exists

select * 
from notification n 
where status = 0 and
(
  exists (select * from notif_user nu where nu.user_id = 1 and nu.notif_id = n.notif_id)
  or exists(select * from notif_group ng where ng.group_id = 1 and ng.notif_id = n.notif_id)
);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!