如何使用關聯表查詢兩種類型的數據:關聯表查詢技巧及優化詳解

如何使用關聯表查詢兩種類型的數據:關聯表查詢技巧及優化詳解

mysql 關聯表查詢詳解

有關關聯表查詢的疑惑,是數據庫開發中一個常見的挑戰。本文將解析一個復雜的查詢,以闡明如何使用關聯表檢索所需數據。

問題描述:

有如下兩個表:

  • a 表,包含以下字段:id 和 outer_id
  • b 表,包含以下字段:id、type

目的:查詢兩種類型的 a 表數據。一種是使用 a 表的 outer_id 關聯到 b 表中存在的 id,且 b 表的 type 不等于 99。另一類型是 b 表必須存在且 type 等于 99。

原始查詢嘗試:

select a.* from a as a where ((select b.type from b as b where b.id = a.outer_id limit 1) is null) or (select b.type from b as b where b.id = a.outer_id limit 1) != 99
select a.* from a as a where (select b.type from b as b where b.id = a.outer_id limit 1) = 99

優化查詢:

根據提供的要求,已優化查詢為:

第一種類型的數據:

select a.* from a a left join b b on b.id = a.outer_id where b.id is null    or (b.id is not null and b.type != 99)

第二種類型的數據:

SELECT a.* FROM A a INNER JOIN B b ON b.id = a.outer_id AND b.type = 99

在優化后的查詢中:

  • 左連接 (left join) 用于獲取第一種數據,其中 b 表可能不存在或者 type 不等于 99。
  • 內連接 (inner join) 用于獲取第二種數據,其中 b 表必須存在且 type 等于 99。

? 版權聲明
THE END
喜歡就支持一下吧
點贊12 分享