我有一個MySQL數據庫,其中表A與表B有一對多關係,並且我希望選擇表B中沒有子表的所有行答:我已經使用只有在沒有子女的情況下選擇父行
SELECT id FROM A WHERE NOT EXISTS (SELECT * FROM B WHERE B.id=A.id)
和
SELECT id FROM A LEFT JOIN B ON A.id=B.id WHERE B.id IS NULL
這兩個似乎慢嘗試。有更快的查詢來實現相同的事情嗎?
如果這是相關的,在我的數據庫表中A有大約500,000行,而表B有大約3到4百萬行。
編輯:對於我的數據庫中的實際表,解釋給我:
+----+--------------------+------------------+-------+---------------+---------------------------+---------+------+---------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+------------------+-------+---------------+---------------------------+---------+------+---------+--------------------------+
| 1 | PRIMARY | frontend_form471 | index | NULL | frontend_form471_61a633e8 | 32 | NULL | 671927 | Using where; Using index |
| 2 | DEPENDENT SUBQUERY | SchoolData | index | PRIMARY | PRIMARY | 49 | NULL | 3121110 | Using where; Using index |
+----+--------------------+------------------+-------+---------------+---------------------------+---------+------+---------+--------------------------+
爲
select number from frontend_form471 where not exists (select * from SchoolData where SchoolData.`f471 Application Number`=frontend_form471.number)
和
+----+-------------+------------------+-------+---------------+---------------------------+---------+------+---------+------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------------+-------+---------------+---------------------------+---------+------+---------+------------------------------------------------+
| 1 | SIMPLE | frontend_form471 | index | NULL | frontend_form471_61a633e8 | 32 | NULL | 671927 | Using index; Using temporary |
| 1 | SIMPLE | SchoolData | index | PRIMARY | PRIMARY | 49 | NULL | 3121110 | Using where; Using index; Not exists; Distinct |
+----+-------------+------------------+-------+---------------+---------------------------+---------+------+---------+------------------------------------------------+
爲
select distinct number from frontend_form471 left join SchoolData on frontend_form471.number=SchoolData.`f471 Application Number` where SchoolData.`f471 Application Number` is NULL
其中在我的情況frontend_form471是表A和SchoolData是表B中
EDIT2:在表B(SchoolData)在我的數據庫,ID是一個兩部分的主鍵的第一部分,所以它是編入索引並且B中仍有多個條目具有相同的ID。
'解析SELECT ID從左邊加入B.在A.id = B.id WHERE B.id IS NULL'你能發佈兩個查詢的EXPLAIN結果嗎? – Igor
索引沒有幫助嗎? – Londeren
是否選擇「COUNT(*)= 0」更快? –