Upgrade to Pro — share decks privately, control downloads, hide ads and more …

【SQL】WITHの使いまわしに 気を付けよう

シノラー
September 08, 2024

【SQL】WITHの使いまわしに 気を付けよう

WITH句はとても便利ですが、使いまわす際には注意が必要です。
そこで、WITHを使い回す際の注意点についてまとめました。

シノラー

September 08, 2024
Tweet

More Decks by シノラー

Other Decks in Programming

Transcript

  1. 記載方法の比較(サブクエリ) SELECT p.first_name, p.last_name, a.street, a.city FROM People p INNER

    JOIN ( SELECT person_id, street, city FROM Addresses WHERE city = 'New York' ) a ON p.person_id = a.person_id;
  2. 記載方法の比較(WITH) WITH Address_CTE AS ( SELECT person_id, street, city FROM

    Addresses WHERE city = 'New York' ) SELECT p.first_name, p.last_name, a.street, a.city FROM People p INNER JOIN Address_CTE a ON p.person_id = a.person_id;
  3. 例(異なる条件でWITHを使いまわす) WITH ADR AS (SELECT person_id, birth_date FROM Addresses )

    SELECT pep.first_name, adr1.birth_date, adr2.birth_date FROM People pep INNER JOIN ADR adr1 ON pep.person_id = adr1.person_id INNER JOIN ADR adr2 ON pep.birth_date = adr2.birth_date WHERE pep.person_id = 135233;
  4. 改善策 1 SELECT  pep.first_name, adr1.address_id, adr2.birth_date FROM People pep INNER

    JOIN ( SELECT person_id, address_id FROM Addresses WHERE person_id = 135233) adr1 ON pep.person_id = adr1.person_id INNER JOIN ( SELECT person_id, birth_date FROM Addresses) adr2 ON pep.birth_date = adr2.birth_date WHERE pep.person_id = 135233;
  5. 改善策 2 CREATE TEMP TABLE temp_addresses AS SELECT person_id, address_id,

    birth_date FROM Addresses WHERE person_id = 135233; SELECT pep.first_name, FROM People pep INNER JOIN temp_addresses adr1 ON pep.person_id = adr1.person_id INNER JOIN temp_addresses adr2 ON pep.birth_date = adr2.birth_date ORDER BY adr1_address_id, adr2_address_id;