[英]How to optimize mysql query with union of two tables having more than 750,000 records in both tables?
我有兩個表propeties_1
和properties_2
。 表propeties_1
有350,000 條記錄,表propeties_2
有400,000 條記錄。
我正在使用查詢如下:
Select union_table.* FROM
(
(select col1 as c1, col2 as c2, col3 as c3 from `propeties_1` where status='A')
union
(select colm1 as c1, colm2 as c2, colm3 as c3 from `propeties_2` where status='A')
) as union_table
limit 12 offset 0 order by c1;
此查詢執行時間過長。
如何優化此查詢?
如果在數據庫上將propeties_1.status
和propeties_2.status
標記為INDEX
,則可以極大地優化查詢。
您可以使用以下說明輕松創建它:
CREATE UNIQUE INDEX index_status1 on propeties_1(status);
CREATE UNIQUE INDEX index_status2 on propeties_2(status);
索引是數據庫搜索引擎可以用來加速數據檢索的特殊查找表。 簡單地說,索引是指向表中數據的指針。 數據庫中的索引與書后的索引非常相似。
這是一個簡單的技巧——將ORDER BY
和LIMIT
添加到內部查詢中。 這里有更多討論,包括如何處理OFFSET
:
http://mysql.rjweb.org/doc.php/pagination#pagination_and_union
並有這些復合索引:
propeties_1: INDEX(status, col1)
propeties_2: INDEX(status, colm1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.