【发布时间】:2017-04-23 08:46:30
【问题描述】:
我在 Mysql 中有以下存储过程。我的列必须是动态的,以便我将行转换为列。我有一个临时表来存储我需要的数据,然后我将行连接为带有 if 语句的列,但是我在 mysql 中出现内存不足错误。有什么方法可以优化我的查询以在 mysql workbench(64 位操作系统和 4gb 内存)中高效工作?
DELIMITER $$
CREATE DEFINER=`root`@`localhost`
PROCEDURE `myWordDistributionsQueryAll`(OUT myOutput text)
BEGIN
CREATE TEMPORARY TABLE IF NOT EXISTS tmpWeightTable
(INDEX(word,topicName) ) ENGINE=MyISAM
AS (
SELECT wwt.topicName, t.topic_cnt as sumOfWordsInTopic,
wwt.word, wwt.wordCount,
(wwt.wordCount / t.topic_cnt) AS wordProbability
FROM weightallofwordsintopic as wwt JOIN
(SELECT topicName, sum(wordCount) AS topic_cnt
FROM weightallofwordsintopic
GROUP BY topicName
) t
ON wwt.topicName = t.topicName
);
SET @sql = '';
SELECT @sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
SELECT
DISTINCT
CONCAT(
'SUM(IF(word = ''',
word,
''', wordProbability, 0)) AS ',
word
) as output
FROM
tmpWeightTable
) as temp;
SET @sql = CONCAT('SELECT topicName, ', @sql, ' FROM tmpWeightTable
group by topicName order by topicName asc');
SET myOutput=@sql;
END$$
DELIMITER ;
表:
CREATE TABLE weightallofwordsintopic (
topicName varchar(200) DEFAULT NULL,
word varchar(100) DEFAULT NULL,
wordCount int(11) DEFAULT NULL,
KEY topicName_index (topicName),
KEY word_index (word)
) ENGINE=InnoDB DEFAULT CHARSET=latin5
【问题讨论】:
-
多少行?请提供
SHOW CREATE TABLE weightallofwordsintopic。GROUP_CONCAT()不会更容易吗? -
您好@RickJames 感谢您的关注,创建表脚本如下 CREATE TABLE
weightallofwordsintopic(topicNamevarchar(200) DEFAULT NULL,wordvarchar(100) DEFAULT NULL,wordCountint(11) 默认 NULL,KEYtopicName_index(topicName),KEYword_index(word) ENGINE=InnoDB DEFAULT CHARSET=latin5;行数太大,可能是 500k,但是当我转换为行时,我使它变得不同。
标签: mysql stored-procedures out-of-memory query-optimization