我的數據庫表的增長速度非常快(並將繼續),在這個時候我有一個問題,這個查詢(當然,其他人也是如此):MySQL的:優化查詢對抗巨大的表
select user_id from post where user_id not in (select id from user)
我需要什麼是張貼表中的新id,並且沒有在用戶表中。
這裏的解釋:
> mysql> explain select user_id from post where user_id not in (select
> id from user);
>
+----+--------------------+-------+-----------------+---------------+---------+---------+------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref |rows | Extra |
+----+--------------------+-------+-----------------+---------------+---------+---------+------+----------+-------------+
| 1 | PRIMARY | post | ALL | NULL |NULL | NULL | NULL | 16076920 | Using where |
| 2 | DEPENDENT SUBQUERY | user | unique_subquery | PRIMARY | PRIMARY | 8 | func | 1 | Using index |
+----+--------------------+-------+-----------------+---------------+---------+---------+------+----------+-------------+
我已經試過這等過:
SELECT p.user_id FROM post p LEFT JOIN user u ON p.user_id=u.id WHERE u.id IS NULL;
的解釋:
mysql> EXPLAIN SELECT p.user_id FROM post p LEFT JOIN user u ON p.user_id=u.id WHERE u.id IS NULL;
+----+-------------+-------+--------+---------------+---------+---------+-----------------+----------+--------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+-----------------+----------+--------------------------------------+
| 1 | SIMPLE | p | ALL | NULL | NULL | NULL | NULL | 14323335 | |
| 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 8 | ghost.p.user_id | 1 | Using where; Using index; Not exists |
+----+-------------+-------+--------+---------------+---------+---------+-----------------+----------+--------------------------------------+
兩個查詢還得看整個表後,它非常龐大: 發表數:16077899條目 用戶表:9657158條目
查詢需要幾分鐘(超過30分鐘)才能執行,任何提示?
謝謝!
你的第二個查詢應該返回很多空行,因爲如果它爲空,u.id只會顯示出來。也許你想要p.user_id。它的運行速度與第一個查詢一樣慢嗎? –
你可以添加表格嗎? – Kickstart
約阿希姆,你是對的,我已經改變了第二個查詢。 – user3364621