首页  >  问答  >  正文

使用多个表进行MySQL连接,避免使用子查询方法

我在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粉442576165P粉442576165408 天前459

全部回复(2)我来回复

  • P粉567281015

    P粉5672810152023-09-08 16:30:03

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

    所以这里没有性能问题。

    回复
    0
  • P粉576184933

    P粉5761849332023-09-08 15:26:05

    您可以将子查询表示为联合查询,并比较执行计划统计信息。查看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)
    );

    回复
    0
  • 取消回复