簡體   English   中英

優化MySQL CREATE TABLE查詢

[英]Optimizing MySQL CREATE TABLE Query

我有兩個表正在嘗試加入第三個查詢,這似乎花費了太長時間。

這是我正在使用的語法

CREATE TABLE active_users
(PRIMARY KEY ix_all (platform_id, login_year, login_month, person_id))
SELECT platform_id
    , YEAR(my_timestamp) AS login_year
    , MONTH(my_timestamp) AS login_month
    , person_id
    , COUNT(*) AS logins
FROM
    my_login_table
GROUP BY 1,2,3,4;

CREATE TABLE active_alerts
(PRIMARY KEY ix_all (platform_id, alert_year, alert_month, person_id))
SELECT platform_id
    , YEAR(alert_datetime) AS alert_year
    , MONTH(alert_datetime) AS alert_month
    , person_id
    , COUNT(*) AS alerts
FROM 
    my_alert_table
GROUP BY 1,2,3,4;

CREATE TABLE all_data
(PRIMARY KEY ix_all (platform_id, theYear, theMonth, person_id))
SELECT a.platform_id
    , a.login_year AS theyear
    , a.login_month AS themonth
    , a.person_id
    , IFNULL(a.logins,0) AS logins
    , IFNULL(b.alerts,0) AS job_alerts
FROM
    active_users a
LEFT OUTER JOIN
    active_alerts b
        ON a.platform_id = b.platform_id
        AND a.login_year = b.alert_year
        AND a.login_month = b.alert_month
        AND a.person_id = b.person_id;

第一個表(登錄)返回大約50萬行,耗時不到1分鍾,第二個表(警報)返回大約20萬行,耗時不到1分鍾。

如果僅運行第三條語句的SELECT部分​​,它將在幾秒鍾內運行,但是,一旦使用CREATE TABLE語法運行它,則將花費30多分鍾。

我嘗試過與主鍵不同的索引類型,例如UNIQUE或INDEX以及根本沒有鍵,但這似乎並沒有太大的區別。

我可以做些什么來加快此表的創建/插入嗎?

編輯:這是顯示創建表語句的輸出

CREATE TABLE `active_users` (
  `platform_id` int(11) NOT NULL,
  `login_year` int(4) DEFAULT NULL,
  `login_month` int(2) DEFAULT NULL,
  `person_id` varchar(40) NOT NULL,
  `logins` bigint(21) NOT NULL DEFAULT '0',
  KEY `ix_all` (`platform_id`,`login_year`,`login_month`,`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

CREATE TABLE `alerts` (
  `platform_id` int(11) NOT NULL,
  `alert_year` int(4) DEFAULT NULL,
  `alert_month` int(2) DEFAULT NULL,
  `person_id` char(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
  `alerts` bigint(21) NOT NULL DEFAULT '0',
  KEY `ix_all` (`platform_id`,`alert_year`,`alert_month`,`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

和EXPLAIN的輸出

id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra

1   SIMPLE  a   (null)  ALL (null)  (null)  (null)  (null)  503504  100 (null)

1   SIMPLE  b   (null)  ALL ix_all  (null)  (null)  (null)  220187  100 Using where; Using join buffer (Block Nested Loop)

這有點hack,但我想出了如何使其運行得更快的方法。

我在平台的第三張表,年,月,人上添加了主鍵

我使用內部聯接插入了相交數據,然后插入忽略左表,並在單獨的語句中添加零警報。

暫無
暫無

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

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