Heim  >  Fragen und Antworten  >  Hauptteil

Verwenden Sie mehrere Tabellen für MySQL-Joins und vermeiden Sie die Verwendung von Unterabfragemethoden

Meine Frage in Fiddle lautet wie folgt.

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

Abfragen funktionieren wie erwartet. Gibt es jedoch Leistungsprobleme bei der Abfrage? Ist es möglich, eine innere Abfrage in eine Verknüpfung umzuwandeln?

P粉442576165P粉442576165408 Tage vor457

Antworte allen(2)Ich werde antworten

  • P粉567281015

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

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

    所以这里没有性能问题。

    Antwort
    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)
    );

    Antwort
    0
  • StornierenAntwort