簡體   English   中英

通過連接表和按每個表中的列排序來優化 MySQL 查詢

[英]Optimize MySQL query with joining tables and ordering by columns from each table

我有一個包含近 90 萬行的列的表組織。

身份證 | 姓名 |

此外,我有一個表收藏夾,其中存儲用戶添加到收藏夾的組織 ID。

身份證 | 用戶 ID | 組織 ID

任務是獲取按組織等級 DESC 排序的前 10 個組織,但無論如何,我們需要顯示用戶最喜歡的組織。 我正在嘗試使用此查詢執行此操作,但需要 10 秒:

SELECT o.*, f.id from organizations o 
LEFT JOIN favorites f ON o.id = f.organization_id AND f.user_id = 1
ORDER BY f.id DESC, o.rank
LIMIT 10

如何優化這個 MySQL 查詢?

我的想法是子查詢:

SELECT o.*, f.id
FROM ((SELECT o.*, NULL as id
       FROM organizations o 
       ORDER BY o.rank DESC
       LIMIT 10
      ) 
      UNION ALL
      (SELECT o.*, f.id
       FROM organizations o JOIN
            favorites f
            ON o.id = f.organization_id AND f.user_id = 1
      )
     ) fo
ORDER BY f.id DESC, o.rank
LIMIT 10;

為此,您需要以下索引organizations(rank) , f(organization_id, user_id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM