【问题标题】:Running reports from busy tables and avoiding locking those tables从繁忙的表运行报告并避免锁定这些表
【发布时间】:2012-03-30 00:55:29
【问题描述】:

我有许多涉及大型数据集连接的报告。这些表每秒被写入很多次。我的 cronjobs 在影响最小的时间运行查询,但我仍然担心用它们锁定表会损害性能。

这是他们今天要求的一个简单示例。它显示 RIIA 报告的播放时间:

SELECT  
    date_format(p.`played`, '%Y-%m') as `month`,
    SUM(TIME_TO_SEC(s.`length`))/3600 as `playtime`
INTO OUTFILE "/tmp/120313_playtime.csv"
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
FROM 
    `plays` p,
    `songs` s
GROUP BY `month`

如何构造它以避免在查询运行时导致无线电应用程序写入播放表的问题?我应该创建临时表并复制实时表吗?

// EDIT per request EXPLAIN 输出

+----+-------------+-------+------+---------------+------+---------+------+---------+---------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows    | Extra                           |
+----+-------------+-------+------+---------------+------+---------+------+---------+---------------------------------+
|  1 | SIMPLE      | s     | ALL  | NULL          | NULL | NULL    | NULL |    3909 | Using temporary; Using filesort |
|  1 | SIMPLE      | p     | ALL  | NULL          | NULL | NULL    | NULL | 4040933 | Using join buffer               |
+----+-------------+-------+------+---------------+------+---------+------+---------+---------------------------------+

CREATE TABLE `plays` (
  `play_id` int(11) NOT NULL auto_increment,
  `song_id` int(11) NOT NULL,
  `played` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  PRIMARY KEY  (`play_id`)
) ENGINE=MyISAM AUTO_INCREMENT=4040992 DEFAULT CHARSET=latin1 COMMENT='play counts for songs' AUTO_INCREMENT=4040992 ;


CREATE TABLE `songs` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(255) NOT NULL,
  `artist_id` int(11) NOT NULL,
  `length` time NOT NULL,
  `album_id` int(11) NOT NULL,
  `active` tinyint(4) NOT NULL,
  `tracknum` varchar(16) NOT NULL,
  `bitrate` varchar(32) NOT NULL,
  `date_created` datetime NOT NULL,
  `date_modified` timestamp NOT NULL default '0000-00-00 00:00:00' on update CURRENT_TIMESTAMP,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4136 DEFAULT CHARSET=latin1 AUTO_INCREMENT=4136 ;

【问题讨论】:

  • 您能从上面的查询中显示EXPLAIN 吗?
  • 现在在主体中添加了解释。表都有一个自动递增的 id 字段。
  • 所以表是相关的,即使用外键?你也可以为两者添加SHOW CREATE TABLE 吗?
  • @ManseUK 是的,plays.song_id 引用了songs.id。创建添加
  • @jerrygarciuh 我没有看到任何外键约束?!?

标签: mysql optimization query-optimization


【解决方案1】:

想到两件直接的事情......第一,戏剧和歌曲之间没有“加入”,这将导致笛卡尔积。其次,添加一个 WHERE 子句,我希望“播放”列是日期/时间,因此您可以查询所有记录

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2021-10-11
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多