前提・実現したいこと
SQLのデータ抽出についての質問です。
同テーブル内のレコードの内、同じカラムのフィールド値が一致するかつ異なるカラムのフィールドの値が一致するレコードを全て抽出したいです。
上記内容をテーブルから取得できるクエリをご教授いただけないでしょうか。
データの取得条件
「CONCAT(test.name1, test.name2)が一致するレコード」
かつ
「CONCAT(test.h_phone1, test.h_phone2, test.h_phone3) とCONCAT(test.m_phone1, test.m_phone2, test.m_phone3)の組み合わせで一致するレコード」
環境
OS:CentOS7
DB:MySQL5.7
※前提としてテーブルには10万件ちかいレコードが入っています。
試したこと・発生している問題
実際にした事としては、サブクエリでテーブル内のレコードを全件取得した後にWHERE句で条件で絞り込む方法です。
テーブルが100件ほどであれば時間がかかる事なく問題なく取得できましたが、
10万件近いデータで試したところパフォーマンスが悪くタイムアウトエラーが発生してしましました。
目安としては10分以内で結果を取得できるクエリが望ましいです。
テーブルのデータ構造
testテーブル
| id | name_1 | name2 | h_phone1 | h_phone2 | h_phone3 | m_phone1 | m_phone2 | m_phone3 |
| ---- | ---- |
| 1 | 佐藤 | 太郎 | 000 | 1111 | 2222 | 000 | 3333 | 4444 |
| 2 | 佐藤 | 太郎 | 000 | 1111 | 2222 | 000 | 1111 | 2222 |
| 3 | 佐藤 | 太郎 | 000 | 3333 | 4444 | 000 | 3333 | 4444 |
| 4 | 佐藤 | 次郎 | 000 | 1111 | 2222 | 000 | 1111 | 2222 |
| 5 | 佐藤 | 三郎 | 000 | 1111 | 2222 | 000 | 3333 | 4444 |
実際に発行したクエリ
SELECT main_test.id, CONCAT(main_test.name1, main_test.name2) AS main_name, CONCAT(sub_test.name1, sub_test.name2) AS sub_name, CONCAT( main_test.h_phone1, main_test.h_phone2, main_test.h_phone3 ) AS main_h_phone, CONCAT( sub_test.m_phone1, sub_test.m_phone2, sub_test.m_phone3 ) AS sub_m_phone, CONCAT( sub_test.h_phone1, sub_test.h_phone2, sub_test.h_phone3 ) AS sub_h_phone, CONCAT( main_test.m_phone1, main_test.m_phone2, main_test.m_phone3 ) AS main_m_phone FROM test AS main_test, ( SELECT test.name1, test.name2, test.h_phone1, test.h_phone2, test.h_phone3, test.m_phone1, test.m_phone2, test.m_phone3 FROM test WHERE -- 「h_phoneが全てNULL・空ではない」もしくは「m_phoneが全てNULL・空ではない」 ( ( ( test.h_phone1 IS NOT NULL AND test.h_phone2 IS NOT NULL AND test.h_phone3 IS NOT NULL ) AND ( test.h_phone1 != "" AND test.h_phone2 != "" AND test.h_phone3 != "" ) ) OR ( ( test.m_phone1 IS NOT NULL AND test.m_phone2 IS NOT NULL AND test.m_phone3 IS NOT NULL ) AND ( test.m_phone1 != "" AND test.m_phone2 != "" AND test.m_phone3 != "" ) ) ) ) AS sub_test WHERE -- 「main_h_phone、sub_m_phone」もしくは「sub_h_phoneとmain_m_phone」の組み合わせ CONCAT(main_test.name1, main_test.name2) = CONCAT(sub_test.name1, sub_test.name2) AND ( ( CONCAT( main_test.h_phone1, main_test.h_phone2, main_test.h_phone3 ) = CONCAT( sub_test.m_phone1, sub_test.m_phone2, sub_test.m_phone3 ) ) OR ( CONCAT( sub_test.h_phone1, sub_test.h_phone2, sub_test.h_phone3 ) = CONCAT( main_test.m_phone1, main_test.m_phone2, main_test.m_phone3 ) ) )
回答4件
あなたの回答
tips
プレビュー