AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-2506

quanta's questions

Martin Hope
quanta
Asked: 2012-10-25 08:53:55 +0800 CST

MySQL: como otimizar o procedimento armazenado?

  • 3
  • MySQL 5.5.28

Executando pt-query-digest em um log de consulta lento, obtenho algo assim:

# 1.2s user time, 10ms system time, 22.30M rss, 114.48M vsz
# Current date: Wed Oct 24 23:44:05 2012
# Hostname: x
# Files: /var/log/mysql/mysql-slow.log
# Overall: 4.07k total, 220 unique, 0.00 QPS, 0.09x concurrency __________
# Time range: 2012-10-04 04:45:56 to 2012-10-24 23:35:52
# Attribute          total     min     max     avg     95%  stddev  median
# ============     ======= ======= ======= ======= ======= ======= =======
# Exec time        158487s     10s   1522s     39s    130s    112s     13s
# Lock time          2489s       0    736s   611ms    73us     16s    35us
# Rows sent          1.16G       0  86.77M 299.28k  25.99k   3.36M    0.99
# Rows examine      21.47G       0   1.12G   5.40M  23.50M  21.71M    0.99
# Query size       326.48k      16  20.85k   82.08  258.32  385.79   31.70

# Profile
# Rank Query ID           Response time    Calls R/Call    Apdx V/M   Item
# ==== ================== ================ ===== ========= ==== ===== ====
#    1 0xD2E9F9911E27D964 12280.9558  7.7%   874   14.0514 0.00  7.84 CALL cpcplus_pre_genjs
#    2 0xA1631F45049C9276 10005.1251  6.3%    25  400.2050 0.00 47... CALL selfserving_banner_addnew
#    3 0xDC7BE1A7B0ACF971  8683.7438  5.5%    15  578.9163 0.00 30... CALL selfserving_campaign_update_inline
...

O cpcplus_pre_genjsprocedimento armazenado: http://fpaste.org/YMXd/

Tente criar o perfil deste armazenado:

mysql> select @@profiling;
+-------------+
| @@profiling |
+-------------+
|           1 |
+-------------+
1 row in set (0.00 sec)

mysql> call reportingdb.cpcplus_pre_genjs();
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (15.24 sec)

Query OK, 0 rows affected (15.24 sec)

mysql> show profiles;
+----------+------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Query_ID | Duration   | Query                                                                                                                                                                                                                                                                                                        |
+----------+------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|     8177 | 0.00015300 | INSERT INTO norep_banner_zone_no_gen_today_tmp1(id,userid,zoneid,location,bannerid)
            SELECT id,userid,zoneid,location,bannerid FROM norep_banner_zone_no_gen_today_tmp                                                                                                                                     |
|     8178 | 0.00075400 | INSERT INTO norep_zonebannertmp_bk(zoneid,block,location,bannerid)
            SELECT  A.zoneid,103,A.location,A.bannerid
            FROM norep_banner_zone_no_gen_today_tmp A
            WHERE  (SELECT COUNT(*) FROM norep_banner_zone_no_gen_today_tmp1 B WHERE B.userid = A.userid AND B.id > A.id) <1                            |
|     8179 | 0.00006600 | INSERT INTO norep_zonebannertmp(zoneid,block,location,bannerid)
            SELECT zoneid,block,location,bannerid FROM    norep_zonebannertmp_bk                                                                                                                                                                      |
|     8180 | 0.00013100 | INSERT INTO norep_banner_channel_tmp(bannerid,channelid,location)
            SELECT A.bannerid,B.`ssv_channelid`,_location
            FROM norep_zonebannertmp_bk A
            INNER JOIN `ox_zones` B ON B.`zoneid` = A.zoneid
            WHERE A.zoneid = _zoneid AND A.location = _location           |
|     8181 | 0.00185200 | UPDATE norep_bannertmp1 A,(
            SELECT  A.bannerid,SUM(D.money) money
            FROM norep_zonebannertmp_bk A   
            INNER JOIN norep_banner_zone_in D ON D.bannerid = A.bannerid AND D.zoneid = A.zoneid AND D.location = A.location         
            WHERE  A.zoneid = _zoneid AND A |
|     8182 | 0.00000900 | COMMIT                                                                                                                                                                                                                                                                                                       |
|     8183 | 0.03358200 | INSERT INTO norep_user_zone_tmp(userid,zoneid,location)
SELECT DISTINCT C.`uid` userid,A.zoneid,A.location
FROM norep_zonebannertmp A
INNER JOIN `ox_banners` B ON B.`bannerid` = A.bannerid
INNER JOIN `ox_campaigns` C ON C.`campaignid` = B.`campaignid`
WHERE C.`revenue_type` = 10                      |
|     8184 | 0.01083300 | UPDATE `selfserving_user_zone_day_tmp` A, norep_user_zone_tmp B
SET A.`num` = A.`num` + 1
WHERE A.`userid` = B.userid AND A.`zoneid` = B.zoneid AND A.`location` = B.location                                                                                                                                |
|     8185 | 0.00175600 | INSERT INTO   `selfserving_user_zone_day_tmp`(  `userid`,  `zoneid`,  `location`,  `num`) 
SELECT A.userid,A.zoneid,A.location,1
FROM norep_user_zone_tmp A
LEFT JOIN `selfserving_user_zone_day_tmp` B ON B.`userid` = A.userid AND B.`zoneid` = A.zoneid AND B.`location` = A.location
WHERE B.`num` IS NU |
|     8186 | 0.11734900 | DELETE FROM `norep_cpcplus_genjs_temp`                                                                                                                                                                                                                                                                       |
|     8187 | 0.02444800 | INSERT INTO   `norep_cpcplus_genjs_temp`(  `bannerid`,  `zoneid`,  `location`,block) 
SELECT DISTINCT `bannerid`,  `zoneid`,  `location`, block FROM norep_zonebannertmp                                                                                                                                     |
|     8188 | 0.01252500 | UPDATE `norep_sys_config` A
SET A.`cpcplus_flag_js`=1                                                                                                                                                                                                                                                        |
|     8189 | 0.01244800 | UPDATE `sys_services_monitoring` A SET A.`time_calc` = CURRENT_TIMESTAMP WHERE A.`id` = 31                                                                                                                                                                                                                   |
|     8190 | 0.00008500 | SELECT 1                                                                                                                                                                                                                                                                                                     |
|     8191 | 0.00002500 | SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ                                                                                                                                                                                                                                                      |
+----------+------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
15 rows in set (0.00 sec)

Alguém pode me ajudar a otimizar isso?

mysql stored-procedures
  • 1 respostas
  • 7663 Views
Martin Hope
quanta
Asked: 2012-10-20 01:52:09 +0800 CST

`mostrar status do procedimento` não lista todos os procedimentos?

  • 1
  • mysql-server-5.5.28-1.el5.remi

Estou puxando os cabelos com este problema: somente o EMS SQL Manager pode listar todos os procedimentos da minha loja (1763). cliente mysql, mysql-workbench, Navicat, ... veja apenas alguns deles.

mysql> show procedure status where db='reportingdb';

...
| reportingdb | 7k_cronjob_log                             | PROCEDURE | user@host | 2012-10-17 10:10:55 | 2012-10-17 10:10:55 | DEFINER       |         | utf8                 | utf8_general_ci      | utf8_general_ci    |
+-------------+--------------------------------------------+-----------+----------------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
146 rows in set (0.05 sec)

Como você pode ver 7k_cronjob_log, é o último procedimento e há apenas 146 linhas. Mas vamos ver o que acontece:

mysql> show create procedure reportingdb.warningserver_getmaxtime_v2\G
*************************** 1. row ***************************
           Procedure: warningserver_getmaxtime_v2
            sql_mode: NO_AUTO_VALUE_ON_ZERO
    Create Procedure: CREATE DEFINER=`user`@`host` PROCEDURE `warningserver_getmaxtime_v2`()
    READS SQL DATA
    DETERMINISTIC
BEGIN
    SELECT `LastTimeCalc` FROM `000_sys_params_v3`;
END
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: utf8_general_ci
1 row in set (0.00 sec)

Alguma ideia?

mysql stored-procedures
  • 1 respostas
  • 2001 Views
Martin Hope
quanta
Asked: 2012-10-04 21:27:10 +0800 CST

Agendador de eventos: sem dados - zero linhas buscadas, selecionadas ou processadas?

  • 2
  • MySQL 5.5.28

O log de erros continua recebendo este erro:

121004 12:08:59 [ERROR] Event Scheduler: [user@ip][reportingdb.tvc_bookingonline_update_status] No data - zero r
ows fetched, selected, or processed 
121004 12:13:59 [ERROR] Event Scheduler: [user@ip][reportingdb.tvc_bookingonline_update_status] No data - zero r
ows fetched, selected, or processed 
121004 12:18:59 [ERROR] Event Scheduler: [user@ip][reportingdb.tvc_bookingonline_update_status] No data - zero r
ows fetched, selected, or processed 

A definição:

mysql> show create event reportingdb.tvc_bookingonline_update_status\G
*************************** 1. row ***************************
               Event: tvc_bookingonline_update_status
            sql_mode: NO_AUTO_CREATE_USER
           time_zone: SYSTEM
        Create Event: CREATE DEFINER=`user`@`ip` EVENT `tvc_bookingonline_update_status` ON SCHEDULE EVERY 5 MINUTE STARTS '2012-07-27 10:08:59' ON COMPLETION NOT PRESERVE ENABLE DO CALL `bo_tvc_booking_supdate_status_booking`( @plstbookingid_destroy)
character_set_client: latin1
collation_connection: latin1_swedish_ci
  Database Collation: utf8_general_ci

mysql> show create procedure reportingdb.bo_tvc_booking_supdate_status_booking\G
*************************** 1. row ***************************
           Procedure: bo_tvc_booking_supdate_status_booking
            sql_mode: 
    Create Procedure: CREATE DEFINER=`user`@`ip` PROCEDURE `bo_tvc_booking_supdate_status_booking`(
        OUT plstbookingid_destroy VARCHAR(1500)
    )
    DETERMINISTIC
BEGIN
    DECLARE  no_found_row INT DEFAULT 0;
    DECLARE _idbooking INT;
    DECLARE _status INT;
    DECLARE _no_contract VARCHAR(25);
    DECLARE _fromdate DATE;
    DECLARE _todate DATE;
    DECLARE _flagsync SMALLINT DEFAULT 0;
    DECLARE _ROWSCOUNT INT DEFAULT 0;
    DECLARE _lstBookDestroy VARCHAR(500);
    DECLARE _lstBookRunning VARCHAR(500);
    DECLARE _lstBookFinish VARCHAR(500);
    #LAY DU LIEU BOOKING
    DECLARE  cur_row CURSOR FOR
        SELECT B.`idbooking`, B.`status`, B.`no_contract`, B.`fromdate`, B.`todate` 
        FROM `tvc_bookings` B       
        WHERE B.`status` IN (1, 2, 3);

    DECLARE EXIT HANDLER FOR SQLEXCEPTION  SET @error=1;
    DECLARE  CONTINUE HANDLER FOR NOT FOUND SET  no_found_row = 1;
    SELECT COUNT(*) INTO _ROWSCOUNT 
    FROM `tvc_bookings` B       
    WHERE B.`status` IN (1, 2, 3);
    IF(_ROWSCOUNT > 0) THEN
            SET AUTOCOMMIT=0;
        #BAT DAU DUYET TUNG BOOKING
        SET plstbookingid_destroy = '';
        SET _lstBookDestroy = 'List bookid destroy: ';
        SET _lstBookRunning = 'List bookid running: ';
        SET _lstBookFinish = 'List bookid finish: ';
        OPEN cur_row;
        FETCH cur_row INTO _idbooking, _status, _no_contract, _fromdate, _todate;
        WHILE no_found_row = 0 DO 
            #KIEM TRA RULE
            IF(_status = 1) THEN
                #IF((_no_contract IS NULL OR _no_contract = '') AND DATEDIFF(_fromdate, CURDATE()) <= 3) THEN
                #MODIFY DEN HET NGAY MOI HUY BOOKING
                #IF((_no_contract IS NULL OR _no_contract = '') AND DATEDIFF(CURDATE(), _fromdate) = 1) THEN#YEU CAU NEW NGAY CHAY = NOW
                IF((_no_contract IS NULL OR _no_contract = '') AND DATEDIFF(CURDATE(), _fromdate) > 0) THEN#YEU CAU NEW NGAY CHAY = NOW
                    CALL `bo_tvc_create_version_booking`( _idbooking, 'Services store huy booking den ngay chay ma chua co HD', 'Services');
                    UPDATE `tvc_bookings`  
                    SET `status` = 4,  
                        `modifiedby` = 'SERVICES',
                        `modifieddate` = CURRENT_TIMESTAMP()
                    WHERE `idbooking` = _idbooking;             
                    #OUT INFO
                    SET _lstBookDestroy = CONCAT(_lstBookDestroy, _idbooking, ',');
                END IF;       
            END IF;#IF(_status = 1)

            IF(_status = 2 AND _no_contract != '') THEN
                IF(_fromdate <= CURDATE()) THEN
                    #CHECK TABLE
                    /*
                    SELECT COUNT(*) INTO _flagsync
                    FROM `bo_tvc_sync_hdcn_thucchay` A
                    WHERE A.`booking_id` = _idbooking AND A.`updated` = 1;
                    */
                    SET _flagsync = 1;#FIX CODE CONNECT HDCN SOON

                    IF(_flagsync > 0) THEN
                        CALL `bo_tvc_create_version_booking`( _idbooking, 'Services store chuyen trang thai hop dong thanh running', 'Services');
                        UPDATE `tvc_bookings`  
                        SET `status` = 3,  
                            `modifiedby` = 'SERVICES',
                            `modifieddate` = CURRENT_TIMESTAMP()
                        WHERE `idbooking` = _idbooking;                             

                        #UPDATE FLAG DA CHUYEN                            
                        UPDATE `bo_tvc_sync_hdcn_thucchay`  
                        SET `updated` = 2
                        WHERE `booking_id` = _idbooking AND `updated` = 1;

                        SET _lstBookRunning = CONCAT(_lstBookRunning, _idbooking, ',');
                    END IF;    
                END IF;

                IF(DATE_ADD(_todate, INTERVAL 1 DAY) <= CURDATE()) THEN
                    CALL `bo_tvc_create_version_booking`( _idbooking, 'Huy book vi het ngay chay ma ko co thuc chay ben hdcn', 'Services');
                    UPDATE `tvc_bookings`  
                    SET `status` = 4,  
                        `modifiedby` = 'SERVICES',
                        `modifieddate` = CURRENT_TIMESTAMP()
                    WHERE `idbooking` = _idbooking;                             

                    #OUT INFO
                    SET _lstBookFinish = CONCAT(_lstBookFinish, _idbooking, ',');
                END IF;
            END IF;#IF(_status = 2 AND _no_contract != '') THEN

            #UPDATE CAC BOOKING DA CHAY XONG
            IF(_status = 3 AND DATE_ADD(_todate, INTERVAL 1 DAY) <= CURDATE()) THEN
                CALL `bo_tvc_create_version_booking`( _idbooking, 'Services store chuyen chuyen booking thanh chay ket thuc', 'Services');
                UPDATE `tvc_bookings`  
                SET `status` = 5,  
                    `modifiedby` = 'SERVICES',
                    `modifieddate` = CURRENT_TIMESTAMP()
                WHERE `idbooking` = _idbooking;                        
                SET _lstBookFinish = CONCAT(_lstBookFinish, _idbooking, ',');
            END IF;#IF(_status = 3 AND DATE_ADD(_todate, INTERVAL 1 DAY) <= CURDATE())
        FETCH cur_row INTO _idbooking, _status, _no_contract, _fromdate, _todate;
        END WHILE;
        CLOSE cur_row;

        #OUT INFO TO SERVICES
        SET plstbookingid_destroy = CONCAT(_lstBookDestroy, '\r\n', _lstBookRunning, '\r\n', _lstBookFinish);
    END IF;
    COMMIT;
END
character_set_client: latin1
collation_connection: latin1_swedish_ci
  Database Collation: utf8_general_ci

O que posso fazer para me livrar desse erro?

mysql stored-procedures
  • 2 respostas
  • 7866 Views
Martin Hope
quanta
Asked: 2012-10-03 15:58:12 +0800 CST

Cluster Percona XtraDB: como ignorar o SST ao iniciar?

  • 2

Existe uma maneira de ignorar o State Snapshot Transfer (SST) na inicialização do Percona XtraDB Cluster Server?

wsrep_sst_mode=skipnão funciona:

121003  6:49:55 Percona XtraDB (http://www.percona.com) 1.1.8-rel28.1 started; 
    log sequence number 82208067084
121003  6:49:55 [ERROR] /usr/sbin/mysqld: unknown variable 'wsrep_sst_mode=skip'
121003  6:49:55 [ERROR] Aborting

Estou usando Percona-XtraDB-Cluster-server-5.5.27-23.6.356.rhel5.

mysql replication
  • 1 respostas
  • 619 Views
Martin Hope
quanta
Asked: 2012-10-02 12:10:39 +0800 CST

mysql.proc continua travando, não pode fazer um mysqldump?

  • 10

Devido a alguns problemas com o InnoDB, vou despejar todos os bancos de dados em um novo servidor:

mysqldump -E -R --all-databases | pv -b | mysql -u root -p -h new.server          

O processo de despejo parou com o erro:

59.9kB assword: 59.9kB 
ERROR 145 (HY000) at line 2970: Table './mysql/proc' is marked as crashed and should 
    be repaired
 228MB 
mysqldump: Got errno 32 on write

Executei o seguinte comando para reparar todas as tabelas em todos os bancos de dados:

mysqlcheck --auto-repair --all-databases

Quando examino o mysql.procstatus, obtenho:

mysql> check table mysql.proc;
+------------+-------+----------+----------+
| Table      | Op    | Msg_type | Msg_text |
+------------+-------+----------+----------+
| mysql.proc | check | status   | OK       |
+------------+-------+----------+----------+
1 row in set (0.02 sec)

No entanto, ainda recebo o mesmo erro ao executar novamente o mysqldumpcomando.

Tenho aproximadamente 2.000 procedimentos de armazenamento. Pode ser esse o motivo do erro?

mysql stored-procedures
  • 2 respostas
  • 11849 Views
Martin Hope
quanta
Asked: 2012-09-28 02:07:49 +0800 CST

ERRO Não é possível encontrar ou abrir a tabela?

  • 5
  • Versão do MySQL: 5.5.24

Devido ao seguinte problema:

mysql> desc reportingdb.v3_zone_date_cpm7k;       
ERROR 1146 (42S02): Table 'reportingdb.v3_zone_date_cpm7k' doesn't exist

/var/log/mysqld.log

120927 16:57:04 [ERROR] Cannot find or open table reportingdb/v3_zone_date_cpm7k#P#pcurrent_2012926 from
the internal data dictionary of InnoDB though the .frm file for the
table exists. Maybe you have deleted and recreated InnoDB data
files but have forgotten to delete the corresponding .frm files
of InnoDB tables, or you have moved .frm files to another database?
or, the table contains indexes that this version of the engine
doesn't support.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-troubleshooting.html
how you can resolve the problem.

(ainda não descobri o motivo)

Os arquivos da tabela ainda existem no datadir:

-rw-rw---- 1 mysql mysql    8932 Sep 26 16:50 /var/lib/mysql/reportingdb/v3_zone_date_cpm7k.frm
-rw-rw---- 1 mysql mysql      84 Sep 26 16:50 /var/lib/mysql/reportingdb/v3_zone_date_cpm7k.par
-rw-rw---- 1 mysql mysql 9437184 Sep 13 17:56 /var/lib/mysql/reportingdb/v3_zone_date_cpm7k#P#MERGER_2012828.ibd
-rw-rw---- 1 mysql mysql 1048576 Sep 27 15:42 /var/lib/mysql/reportingdb/v3_zone_date_cpm7k#P#MERGER_2012926.ibd

Esta é a tabela DDL de um backup de um mês (portanto, as partições foram alteradas), mas para referência:

CREATE TABLE `v3_zone_date_cpm7k` ( 
 `campaignid` mediumint(9) NOT NULL DEFAULT '0' COMMENT 'sub_campaignid', 
 `zoneid` smallint(6) NOT NULL DEFAULT '0', 
 `bannerid` mediumint(9) NOT NULL DEFAULT '0', 
 `totalclick` mediumint(9) unsigned NOT NULL DEFAULT '0', 
 `realclick` mediumint(9) unsigned NOT NULL DEFAULT '0', 
 `clickcharge` mediumint(9) NOT NULL DEFAULT '0', 
 `totalview` mediumint(9) unsigned NOT NULL DEFAULT '0', 
 `viewcharge` mediumint(9) unsigned NOT NULL DEFAULT '0', 
 `dt` date NOT NULL DEFAULT '0000-00-00', 
 `partnerid` smallint(6) unsigned NOT NULL DEFAULT '0', 
 KEY `ix_zoneid` (`zoneid`,`dt`), 
 KEY `ix_dt` (`dt`), 
 KEY `ix_campaignid` (`bannerid`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 
/*!50100 PARTITION BY RANGE (TO_DAYS(dt)) 
(PARTITION p00 VALUES LESS THAN (0) ENGINE = InnoDB, 
PARTITION p04 VALUES LESS THAN (734965) ENGINE = InnoDB, 
PARTITION p05 VALUES LESS THAN (735025) ENGINE = InnoDB, 
PARTITION MERGER_2012822 VALUES LESS THAN (735102) ENGINE = InnoDB, 
PARTITION pcurrent_2012822 VALUES LESS THAN (735103) ENGINE = InnoDB, 
PARTITION pcurrent_2012823 VALUES LESS THAN (735104) ENGINE = InnoDB)*/

Vou recuperar esta tabela siga este guia. Mas em 2c. passo, recebo os erros abaixo:

mysql> alter table v3_zone_date_cpm7k_restore discard tablespace;
ERROR 1031 (HY000): Table storage engine for 'v3_zone_date_cpm7k_restore' doesn't have this option

http://bugs.mysql.com/bug.php?id=52422

O que eu posso fazer agora?


ATUALIZAR

Estou restaurando a partir do backup, qual é o procedimento correto para se livrar desse problema?

O que eu tentei (no outro servidor):

  1. DROP TABLE --> ainda obtém o "não existe"

  2. Parar o MySQL

    • Mova todos os arquivos da tabela para outro local

    • Copie os arquivos de backup para o banco de dados correspondente

    • Inicie o MySQL:


    120927 19:12:07  InnoDB: Error: table 'reportingdb/v3_zone_date_cpm7k#P#MERGER_2012828'
    InnoDB: in InnoDB data dictionary has tablespace id 741528,
    InnoDB: but tablespace with that id or name does not exist. Have
    InnoDB: you deleted or moved .ibd files?
    InnoDB: This may also be a table created with CREATE TEMPORARY TABLE
    InnoDB: whose .ibd and .frm files MySQL automatically removed, but the
    InnoDB: table still exists in the InnoDB internal data dictionary.
    InnoDB: Please refer to
    InnoDB: http://dev.mysql.com/doc/refman/5.5/en/innodb-troubleshooting-datadict.html
    InnoDB: for how to resolve the issue.
    InnoDB: We removed now the InnoDB internal data dictionary entry
    InnoDB: of table `reportingdb`.`v3_zone_date_cpm7k` /* Partition `MERGER_2012828` */.
    120927 19:12:07  InnoDB: error: space object of table 'reportingdb/v3_zone_date_cpm7k#P#MERGER_2012926',
    InnoDB: space id 921829 did not exist in memory. Retrying an open.
    120927 19:12:07  InnoDB: Error: table `reportingdb`.`v3_zone_date_cpm7k` /* Partition `pcurrent_2012926`
*/ does not exist in
     the InnoDB internal
    InnoDB: data dictionary though MySQL is trying to drop it.
    InnoDB: Have you copied the .frm file of the table to the
    InnoDB: MySQL database directory from another database?
    InnoDB: You can look for further help from
    InnoDB: http://dev.mysql.com/doc/refman/5.5/en/innodb-troubleshooting.html

ATUALIZAÇÃO Sex 28 de setembro 08:21:49 ICT 2012

Siga sua sugestão, tenho:

  • parou o MySQL
  • movido v3_zone_date_cpm7k* para outro local
  • iniciou o MySQL
  • importou o arquivo .sql e deu o erro:

    ERRO 1050 (42S01) na linha 25: Tabela ' reportingdb. v3_zone_date_cpm7k/* Partição p00*/' já existe

o log de erros mostra:

120928  8:26:42  InnoDB: Warning: trying to init to the tablespace memory cache
InnoDB: a tablespace 932889 of name './reportingdb/v3_zone_date_cpm7k#P#p00.ibd',
InnoDB: but a tablespace 932783 of the same name
InnoDB: already exists in the tablespace memory cache!
InnoDB: We assume that InnoDB did a crash recovery, and you had
InnoDB: an .ibd file for which the table did not exist in the
InnoDB: InnoDB internal data dictionary in the ibdata files.
InnoDB: We assume that you later removed the .ibd and .frm files,
InnoDB: and are now trying to recreate the table. We now remove the
InnoDB: conflicting tablespace object from the memory cache and try
InnoDB: the init again.

e o .idbarquivo é criado automaticamente após a reinicialização:

# ls -l /var/lib/mysql/reportingdb/v3_zone_date_cpm7k#P#p00.ibd 
-rw-rw---- 1 mysql mysql 65536 Sep 28 08:35 /var/lib/mysql/reportingdb/v3_zone_date_cpm7k#P#p00.ibd
mysql innodb
  • 3 respostas
  • 26619 Views
Martin Hope
quanta
Asked: 2012-07-24 22:23:49 +0800 CST

--replicate-wild-ignore-table não funciona?

  • 2

De acordo com o documento sobre replicação e tabelas temporárias , estou configurando --replicate-wild-ignore-tablea opção %.norep%para evitar que tabelas temporárias sejam replicadas:

*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.6.129
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000861
          Read_Master_Log_Pos: 332610533
               Relay_Log_File: mysqld-relay-bin.001578
                Relay_Log_Pos: 9061317
        Relay_Master_Log_File: mysql-bin.000861
             Slave_IO_Running: Yes
            Slave_SQL_Running: No
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: %.norep%
                   Last_Errno: 1146
                   Last_Error: Error 'Table 'reportingdb.norep_cp_banner_tvc_temp_' doesn't exist' on query. Default database: 'reportingdb'. Query: 'UPDATE `ox_banners` A
    SET A.`status` =1
    WHERE A.`bannerid` IN (SELECT bannerid FROM norep_cp_banner_tvc_temp_)'
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 330271548
              Relay_Log_Space: 13544924166
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 1146
               Last_SQL_Error: Error 'Table 'reportingdb.norep_cp_banner_tvc_temp_' doesn't exist' on query. Default database: 'reportingdb'. Query: 'UPDATE `ox_banners` A
    SET A.`status` =1
    WHERE A.`bannerid` IN (SELECT bannerid FROM norep_cp_banner_tvc_temp_)'
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 4

Mas, como você pode ver na show slave status\Gsaída acima, essa instrução ainda é replicada para o escravo e causa o erro.

Há algum problema com a minha consulta? Só tem efeito com as tabelas principais (quero dizer ox_bannersneste caso)?


Responder a @Aaron Brown:

Isso pode ser um tanto surpreendente, mas esse erro é a prova de que seu filtro de replicação está funcionando .

+1.

A primeira pergunta a se fazer é por que estou filtrando a replicação? Raramente há uma boa razão para isso e geralmente causa muito mais problemas do que resolve.

Devido ao problema com tabelas temporárias: Como tornar a replicação do MySQL confiável?

Definitivamente, você pode contornar o problema usando a replicação baseada em linha (RBR) em vez da replicação baseada em instrução (SBR). O RBR replica as alterações nos dados em vez da instrução.

Vou considerar mudar de baseado em misto para baseado em linha.

mysql replication
  • 2 respostas
  • 5439 Views
Martin Hope
quanta
Asked: 2012-07-20 03:48:26 +0800 CST

MySQL: InnoDB continua travando - como recuperar?

  • 3
# free -m
             total       used       free     shared    buffers     cached
Mem:         48289      35288      13000          0        347      30399
-/+ buffers/cache:       4541      43747
Swap:         8189         51       8137
  • mysql-server-5.5.25a-1.el5.remi
  • my.cnf: http://fpaste.org/PQLU/

O MySQL não pode iniciar com os erros abaixo em /var/log/mysqld.log: http://fpaste.org/4VMB/

Só pode ser iniciado ao adicionar innodb_force_recovery = 1a my.cnf, mas recebo outro erro ao iniciar o servidor: http://fpaste.org/6azJ/

Este servidor costumava ser o mestre, mas consegui promover um escravo como o novo mestre. No momento, estou tentando configurar esse mestre com falha como um novo escravo, mas não consigo iniciá-lo.

O que eu deveria fazer agora?


ATUALIZAÇÃO Qui 19 de julho 23:50:17 ICT 2012:

Foi iniciado com sucesso com innodb_force_recovery=2, mas o MySQL desaparece ao fazer um DROP TABLE:

mysql> drop table reportingdb.bigdata_banner_scheduler;
ERROR 2013 (HY000): Lost connection to MySQL server during query

Aqui estão os logs: http://fpaste.org/M82a


ATUALIZAÇÃO Sex 20 de julho 08:02:57 ICT 2012:

Estou tentando reconstruir a replicação usando o Percona Xtrabackup . Na primeira vez, recebo esse bug ao copiar com innobackupex. Obrigado a @DTest que sugere aumentar innodb_log_file_sizepara 1 GB e está tudo bem.

Observe que: você deve copiar innodb_*as configurações do mestre para o escravo e executar innobackupex --apply-log /path/to/datadirno escravo se não quiser obter os erros abaixo:

120720  6:18:50  InnoDB: Error: page 3670052 log sequence number 8078993744933
InnoDB: is in the future! Current system log sequence number 8078561559052.
InnoDB: Your database may be corrupt or you may have copied the InnoDB
InnoDB: tablespace but not the InnoDB log files. See
InnoDB: http://dev.mysql.com/doc/refman/5.5/en/forcing-innodb-recovery.html
InnoDB: for more information.
InnoDB: Error: trying to access page number 2175909760 in space 0,
InnoDB: space name ./ibdata1,
InnoDB: which is outside the tablespace bounds.
InnoDB: Byte offset 0, len 16384, i/o type 10.
InnoDB: If you get this error at mysqld startup, please check that
InnoDB: your my.cnf matches the ibdata files that you have in the
InnoDB: MySQL server.
120720  6:18:50  InnoDB: Assertion failure in thread 47633462918272 in file fil0fil.c line 4434
InnoDB: We intentionally generate a memory trap.
InnoDB: Submit a detailed bug report to http://bugs.mysql.com.
InnoDB: If you get repeated assertion failures or crashes, even
InnoDB: immediately after the mysqld startup, there may be
InnoDB: corruption in the InnoDB tablespace. Please refer to
InnoDB: http://dev.mysql.com/doc/refman/5.5/en/forcing-innodb-recovery.html
InnoDB: about forcing recovery.
23:18:50 UTC - mysqld got signal 6 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed, 
something is definitely wrong and this may fail.

Mas o jogo NÃO acabou: o escravo continua travando depois de alguns minutos:

120720  7:58:28 [Warning] Slave SQL: Could not execute Write_rows event on table reportingdb.ox_banners; Duplicate entry '14
5928' for key 'PRIMARY', Error_code: 1062; handler error HA_ERR_FOUND_DUPP_KEY; the event's master log mysql-bin.000999, end
_log_pos 337836040, Error_code: 1062
120720  7:58:28 [Warning] Slave SQL: Could not execute Write_rows event on table reportingdb.selfserving_img_signatures; Dup
licate entry '145928' for key 'PRIMARY', Error_code: 1062; handler error HA_ERR_FOUND_DUPP_KEY; the event's master log mysql
-bin.000999, end_log_pos 337843612, Error_code: 1062
120720  7:58:28 [Warning] Slave SQL: Could not execute Write_rows event on table reportingdb.selfserving_email_log; Duplicat
e entry '173213' for key 'PRIMARY', Error_code: 1062; handler error HA_ERR_FOUND_DUPP_KEY; the event's master log mysql-bin.
000999, end_log_pos 337844062, Error_code: 1062
00:58:29 UTC - mysqld got signal 11 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed, 
something is definitely wrong and this may fail.

key_buffer_size=1048576
read_buffer_size=1048576
max_used_connections=4
max_threads=2000
thread_count=2
connection_count=2
It is possible that mysqld could use up to 
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 4119820 K  bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x11cc5f20
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 40c73a78 thread_stack 0x40000
/usr/libexec/mysqld(my_print_stacktrace+0x2e)[0x7af52e]
/usr/libexec/mysqld(handle_fatal_signal+0x3e2)[0x67c242]
/lib64/libpthread.so.0[0x3fed00ebe0]
/usr/libexec/mysqld(_ZN13st_select_lex17mark_as_dependentEPS_+0x4d)[0x568a3d]
/usr/libexec/mysqld[0x68cc02]
/usr/libexec/mysqld(_ZN10Item_field15fix_outer_fieldEP3THDPP5FieldPP4Item+0x670)[0x690c90]
/usr/libexec/mysqld(_ZN10Item_field10fix_fieldsEP3THDPP4Item+0x351)[0x691361]
/usr/libexec/mysqld(_ZN9Item_func10fix_fieldsEP3THDPP4Item+0x1d3)[0x6cb433]
/usr/libexec/mysqld(_Z11setup_condsP3THDP10TABLE_LISTS2_PP4Item+0x1a5)[0x53aae5]
/usr/libexec/mysqld(_Z20mysql_prepare_updateP3THDP10TABLE_LISTPP4ItemjP8st_order+0x118)[0x5df3e8]
/usr/libexec/mysqld(_Z12mysql_updateP3THDP10TABLE_LISTR4ListI4ItemES6_PS4_jP8st_ordery15enum_duplicatesbPySB_+0x2b4)[0x5e0134]
/usr/libexec/mysqld(_Z21mysql_execute_commandP3THD+0x239b)[0x575c5b]
/usr/libexec/mysqld(_Z11mysql_parseP3THDPcjP12Parser_state+0x10a)[0x57994a]
/usr/libexec/mysqld(_ZN15Query_log_event14do_apply_eventEPK14Relay_log_infoPKcj+0xc57)[0x734757]
/usr/libexec/mysqld(_Z26apply_event_and_update_posP9Log_eventP3THDP14Relay_log_info+0x16e)[0x516fce]
/usr/libexec/mysqld[0x51e631]
/usr/libexec/mysqld(handle_slave_sql+0xc46)[0x51f946]
/lib64/libpthread.so.0[0x3fed00677d]
/lib64/libc.so.6(clone+0x6d)[0x3fec8d325d]

Trying to get some variables.
Some pointers may be invalid and cause the dump to abort.
Query (128380d7): UPDATE `ox_banners` A
        SET A.locationAd=@locCP 
        WHERE A.zoneId = NAME_CONST('_zoneid',2452)
Connection ID (thread ID): 2061
Status: NOT_KILLED

slave-skip-errors = 1062parece não funcionar.

Vou tirar um instantâneo do Mestre usando mysqldump, espero que resolva o problema de travamento.

mysql replication
  • 1 respostas
  • 15755 Views
Martin Hope
quanta
Asked: 2012-02-06 22:05:40 +0800 CST

LOAD DATA (400k rows) INFILE leva cerca de 7 minutos, não pode matar o processo de "logging slow query"?

  • 3

Versão do MySQL: 5.5.13

A consulta que estou usando:

SET AUTOCOMMIT=0; 
LOAD DATA INFILE '/data10/select_into.outfile/v3_zone_date.out' INTO TABLE v3_zone_date FIELDS TERMINATED BY  ','; 
COMMIT;

Normalmente, leva 3s para ser concluído. Mas, às vezes, a consulta de inserção leva cerca de 3 a 7 minutos para ser executada:

     Id: 97
   User: tom
   Host: 192.168.6.31:27059
     db: test
Command: Query
   Time: 155
  State: logging slow query
   Info: COMMIT

e meu banco de dados está completamente bloqueado (muito lento ao conectar). O ID do processo 97 continua em execução depois que tento eliminá-lo. O script init mostra o sinalizador [FAILED] ao tentar reiniciar o MySQL, então devo usar kill -9e começar de novo.

Vou tentar desabilitar o unique_checkssiga este guia. Mas estou tentando descobrir por que está trancado.

Existem alguns Waiting for table metadata lockestados em tabelas temporárias:

     Id: 180098
   User: jerry
   Host: 192.168.6.31:54909
     db: test
Command: Query
   Time: 142
  State: Waiting for table metadata lock
   Info: DROP TABLE IF EXISTS norep_locationtmp

e um Waiting for table level lockestado:

     Id: 180233
   User: bob
   Host: 192.168.6.31:43537
     db: test
Command: Query
   Time: 65
  State: Waiting for table level lock
   Info: SELECT COUNT(DISTINCT A.`campaignid`)  INTO _c
FROM `ox_campaigns` A 
INNER JOIN `selfserving_users` B ON B.`user_id` = A.`uid`
INNER JOIN `v3_cam_date` C ON C.`campaignid` = A.`campaignid`
WHERE A.`revenue_type` = 5 AND A.`deleted` = 0 AND A.`expire` = DATE_ADD(CURRENT_DATE, INTERVAL 1 DAY) 
AND A.`isExpired` = 0 AND IF( NAME_CONST('_permitid',3) = -1, 1=1, IF( NAME_CONST('_permitid',3) = 0, A.`uid` IN (SELECT C.`user_id` FROM `selfserving_users` C WHERE C.`groupid` =  NAME_CONST('_groupid',12) ) ,A.`uid` =  NAME_CONST('userid',388)))

Não há nada relacionado à tabela acima - v3_zone_datee nenhum impasse detectado em SHOW ENGINE INNODB STATUS. Onde devo dar uma olhada primeiro para solucionar este caso? Deixe-me saber se você precisar de mais informações.


Responder a @RolandoMySQLDBA:

A parte assustadora sobre a consulta é a auto-referência

Você está selfserving_usersagindo de maneira egoísta contra si mesmo.

Vou pedir ao desenvolvedor para reescrevê-lo.

  • Você está martelando o Buffer InnoDB
  • Alguma troca de memória pode estar acontecendo

Eu tenho 40 GB de RAM e:

innodb_buffer_pool_size     = 20G
innodb_buffer_pool_instances    = 8

O gráfico de memória exibe que não há aumento.

Possíveis problemas de bloqueio de tabela completa que estão afetando as páginas de dados fora da v3_zone_datetabela (como aconteceu com a selfserving_users tabela)

Você tem alguma ideia para evitar o problema de bloqueio de tabela completa?

Pode haver uma maneira de acelerar o processo LOAD DATA INFILE em uma tabela InnoDB. Não posso dar uma resposta sólida sobre isso, mas tente este link do Barão Schwartz.

Vou tentar o método fifo e informo o resultado.


ATUALIZAÇÃO: quarta-feira, 22 de fevereiro 12:19:03 ICT 2012

Abaixo está o trecho da SHOW ENGINE INNODB STATUSsaída ao pendurar:

---TRANSACTION 1EF3CC26, ACTIVE (PREPARED) 332 sec
68 lock struct(s), heap size 14776, 6933 row lock(s), undo log entries 3465
MySQL thread id 4088, query id 11411947 192.168.6.31 bob
COMMIT
Trx read view will not see trx with id >= 1EF3CC27, sees < 1EF06C8E

Com base no ID do thread, descobri que o culpado é um processo .NET que está carregando dados no banco de dados seguindo as etapas:

  • BLOQUEIO DE MESAS;
  • SET autocommit=0;
  • SET verificações_únicas=0;
  • SET checagem_chave_externa=0;
  • CARREGAR DADOS;
  • COMPROMETER-SE;
  • DESBLOQUEAR MESAS;
  • SET verificações_únicas=1;
  • SET Foreign_key_checks=1;

Parece que o processamento de inserção trava na etapa COMMIT, a tabela não pode ser desbloqueada e congelando meu banco de dados. Devo trocar a etapa COMMIT e UNLOCK TABLES?

De acordo com o documento MySQL:

A partir do MySQL 5.5.5, não é mais possível definir @@session.sql_log_bin em uma transação ou subconsulta. (Bug #53437)

Pelo que entendi, 400 mil linhas não são grandes o suficiente, não consigo descobrir por que bloqueou meu banco de dados?

Alguma ideia?

mysql innodb
  • 2 respostas
  • 7131 Views
Martin Hope
quanta
Asked: 2011-12-24 03:23:06 +0800 CST

Como tornar a replicação do MySQL confiável?

  • 3
  • Versão principal: 5.5.13-1
  • Versão escrava: 5.5.14-1
  • Formato de registro binário: MIXED

Meu banco de dados Escravo (~ 40 GB) está fora de sincronia com o Mestre. Não consigo encontrar nada interessante no log de erros. Google me dá um link muito útil .

Vou sincronizar novamente o banco de dados, siga esta instrução para minimizar o tempo de inatividade no mestre. Mas antes de fazer isso, só quero ter certeza de que essa situação será limitada no futuro. Vou examinar as partes acima para mostrar o que fiz:

  • O banco de dados escravo foi configurado com a read-onlyopção
  • Há algumas consultas inseguras. Ele apresenta alguns problemas com a replicação baseada em MIXED?
  • Eu repliquei todos os bancos de dados
  • Eu usei os mecanismos de armazenamento InnoDB e MyISAM
  • Os desenvolvedores usam muitas tabelas temporárias

Eu devo:

  • Não use as consultas inseguras
  • Peça aos desenvolvedores que coloquem todas as tabelas temporárias em um banco de dados separado

Mais alguma coisa? Em caso de dessincronização, é mk-table-syncconfiável o suficiente para ressincronizar automaticamente? Alguém usa na produção?


ATUALIZAÇÃO: terça-feira, 28 de fevereiro 23:27:13 ICT 2012

Meu banco de dados Escravo (~ 40 GB) está fora de sincronia com o Mestre. Não consigo encontrar nada interessante no log de erros.

Para obter mais informações sobre o que estava acontecendo, o Slave deve ser iniciado com --log-warnings=2.

mysql replication
  • 1 respostas
  • 2664 Views
Martin Hope
quanta
Asked: 2011-12-23 03:05:09 +0800 CST

Impasse do MySQL - não pode reiniciar normalmente?

  • 6

MySQL versão 5.5.13-1

Um trecho do SHOW ENGINE INNODB STATUS\G:

LATEST DETECTED DEADLOCK
------------------------
111218 10:22:34
*** (1) TRANSACTION:
TRANSACTION 1318D95B, ACTIVE 0 sec starting index read
mysql tables in use 6, locked 6
LOCK WAIT 53 lock struct(s), heap size 14776, 77 row lock(s)
MySQL thread id 60933, query id 124472414 192.168.6.31 thanhnt Copying to tmp table
INSERT INTO usertmp(userid,npayvalue,balance)       
    SELECT B.`userid`, SUM(C.`moneyv`) a,(B.`balance` + B.`promotions`+ B.`promotions1`+ B.`overdraft`) b
    FROM `ox_campaigns` A
    INNER JOIN `v3_cam_date` C ON C.`campaignid` = A.`campaignid`
    INNER JOIN `selfserving_users_balances` B ON B.`userid` = A.`uid`
    INNER JOIN `selfserving_users` F ON F.`user_id` = B.`userid`
    INNER JOIN `selfserving_users_group_balances` E ON E.`groupid` = F.`groupid` AND E.`ispostpaid` = 0
    WHERE A.`revenue_type` = 6 AND C.`dt` BETWEEN A.`activate` AND A.`expire` AND C.`dt` >=  (SELECT DATE_ADD( A.ssv_payment_date_lastest, INTERVAL 1 DAY)  FROM `000_sys_params_v3` A)
    AND C.`viewcharge` >0 
    GROUP BY B.`userid`
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 222397 page no 2576 n bits 304 index `GEN_CLUST_INDEX` of table `reportingdb`.`v3_cam_date` /* Partition `p3` */ trx id 1318D95B lock mode S locks rec but not gap waiting
Record lock, heap no 170 PHYSICAL RECORD: n_fields 15; compact format; info bits 0
 0: len 6; hex 0000a61821ff; asc     ! ;;
 1: len 6; hex 00000b168ac0; asc       ;;
 2: len 7; hex 5200035d760432; asc R  ]v 2;;
 3: len 3; hex 8f661d; asc  f ;;
 4: len 3; hex 0000ac; asc    ;;
 5: len 4; hex 000cc08c; asc     ;;
 6: len 3; hex 0000ac; asc    ;;
 7: len 3; hex 000000; asc    ;;
 8: len 4; hex 000852a6; asc   R ;;
 9: len 3; hex 0519d2; asc    ;;
 10: len 3; hex 00009b; asc    ;;
 11: len 3; hex 8fb747; asc   G;;
 12: len 3; hex 800000; asc    ;;
 13: len 4; hex 00000000; asc     ;;
 14: len 4; hex 00249eda; asc  $  ;;

    ...

*** (2) TRANSACTION:
TRANSACTION 1318D958, ACTIVE 1 sec inserting, thread declared inside InnoDB 123
mysql tables in use 3, locked 3
4808 lock struct(s), heap size 555448, 1122860 row lock(s), undo log entries 7058
MySQL thread id 130380, query id 124472416 192.168.6.31 thanhnt
LOAD DATA INFILE '/data10/select_into.outfile/v3_cam_date.out' INTO TABLE v3_cam_date FIELDS TERMINATED BY  ','
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 222397 page no 2576 n bits 304 index `GEN_CLUST_INDEX` of table `reportingdb`.`v3_cam_date` /* Partition `p3` */ trx id 1318D958 lock_mode X
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 222397 page no 6296 n bits 1000 index `ix_campaignid_dt` of table `reportingdb`.`v3_cam_date` /* Partit
ion `p3` */ trx id 1318D958 lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 213 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
 0: len 3; hex 8f63a5; asc  c ;;
 1: len 3; hex 8fb73b; asc   ;;;
 2: len 6; hex 0000a617374f; asc     7O;;

*** WE ROLL BACK TRANSACTION (1)

Em algum momento, ele combina com um enorme "Waiting for global read lock" no SHOW FULL PROCESSLIST\Ge meu banco de dados está completamente bloqueado. Não é possível reiniciar com o script init, então devo fazer um kill -9 <PID>(isso causa muitas tabelas travadas).

O InnoDB Lock Monitor foi ativado, siga este guia. information_schema.innodb_locksestá vazio e abaixo está a innodb_trxtabela:

*************************** 1. row ***************************
                    trx_id: 135937A0
                 trx_state: RUNNING
               trx_started: 2011-12-19 11:16:04
     trx_requested_lock_id: NULL
          trx_wait_started: NULL
                trx_weight: 43929
       trx_mysql_thread_id: 257731
                 trx_query: INSERT INTO `__tZoneTempTable` (zoneid, rc, v, dt)  
    (SELECT a.`zoneid`, sum(a.`realclick`) as rc, sum(a.`totalview`) as v , a.`dt` FROM `v3_zone_date` a INNER JOIN `ox_zones` b ON a.`zoneid` = b.`zoneid` where b.`is_smallbiz` = 3 AND b.`deleted` = 0 AND a.`zoneid` > 0 AND a.`dt` =  NAME_CONST('_date',_latin1'2011-12-17' COLLATE 'latin1_swedish_ci') GROUP BY a.`zoneid`)
       trx_operation_state: fetching rows
         trx_tables_in_use: 10
         trx_tables_locked: 9
          trx_lock_structs: 43929
     trx_lock_memory_bytes: 6093240
           trx_rows_locked: 15961781
         trx_rows_modified: 0
   trx_concurrency_tickets: 359
       trx_isolation_level: REPEATABLE READ
         trx_unique_checks: 1
    trx_foreign_key_checks: 1
trx_last_foreign_key_error: NULL
 trx_adaptive_hash_latched: 0
 trx_adaptive_hash_timeout: 10000
*************************** 2. row ***************************
                    trx_id: 13590BD9
                 trx_state: RUNNING
               trx_started: 2011-12-19 11:15:23
     trx_requested_lock_id: NULL
          trx_wait_started: NULL
                trx_weight: 43929
       trx_mysql_thread_id: 257456
                 trx_query: INSERT INTO `__tZoneTempTable` (zoneid, rc, v, dt)  
    (SELECT a.`zoneid`, sum(a.`realclick`) as rc, sum(a.`totalview`) as v , a.`dt` FROM `v3_zone_date` a INNER JOIN `ox_zones` b ON a.`zoneid` = b.`zoneid` where b.`is_smallbiz` = 3 AND b.`deleted` = 0 AND a.`zoneid` > 0 AND a.`dt` =  NAME_CONST('_date',_latin1'2011-12-17' COLLATE 'latin1_swedish_ci') GROUP BY a.`zoneid`)
       trx_operation_state: fetching rows
         trx_tables_in_use: 10
         trx_tables_locked: 9
          trx_lock_structs: 43929
     trx_lock_memory_bytes: 6093240
           trx_rows_locked: 15961781
         trx_rows_modified: 0
   trx_concurrency_tickets: 359
       trx_isolation_level: REPEATABLE READ
         trx_unique_checks: 1
    trx_foreign_key_checks: 1
trx_last_foreign_key_error: NULL
 trx_adaptive_hash_latched: 0
 trx_adaptive_hash_timeout: 10000
*************************** 3. row ***************************
                    trx_id: 1358EA92
                 trx_state: RUNNING
               trx_started: 2011-12-19 11:14:57
     trx_requested_lock_id: NULL
          trx_wait_started: NULL
                trx_weight: 0
       trx_mysql_thread_id: 257363
                 trx_query: NULL
       trx_operation_state: NULL
         trx_tables_in_use: 0
         trx_tables_locked: 0
          trx_lock_structs: 0
     trx_lock_memory_bytes: 376
           trx_rows_locked: 0
         trx_rows_modified: 0
   trx_concurrency_tickets: 0
       trx_isolation_level: REPEATABLE READ
         trx_unique_checks: 1
    trx_foreign_key_checks: 1
trx_last_foreign_key_error: NULL
 trx_adaptive_hash_latched: 0
 trx_adaptive_hash_timeout: 10000

Como sugeriu @Chris, gostaria de fornecer as SHOW CREATE TABLEsaídas:

mysql> show create table v3_cam_date\G
*************************** 1. row ***************************
       Table: v3_cam_date
Create Table: CREATE TABLE `v3_cam_date` (
  `campaignid` mediumint(9) NOT NULL DEFAULT '0',
  `totalclick` mediumint(9) unsigned NOT NULL DEFAULT '0',
  `totalview` int(11) unsigned NOT NULL DEFAULT '0',
  `realclick` mediumint(9) unsigned NOT NULL DEFAULT '0',
  `clickcharge` mediumint(9) unsigned NOT NULL DEFAULT '0',
  `viewcharge` int(11) unsigned NOT NULL DEFAULT '0',
  `uv` mediumint(9) unsigned NOT NULL DEFAULT '0',
  `uc` mediumint(9) unsigned NOT NULL DEFAULT '0',
  `dt` date NOT NULL DEFAULT '0000-00-00',
  `ctr` decimal(5,3) NOT NULL DEFAULT '0.000' COMMENT '=-1: meaning not available(N/A)',
  `moneyc` int(11) unsigned NOT NULL DEFAULT '0',
  `moneyv` int(11) unsigned NOT NULL DEFAULT '0',
  KEY `ix_campaignid_dt` (`campaignid`,`dt`),
  KEY `ix_dt` (`dt`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
/*!50100 PARTITION BY RANGE (TO_DAYS(dt))
(PARTITION p0 VALUES LESS THAN (0) ENGINE = InnoDB,
 PARTITION p01 VALUES LESS THAN (734502) ENGINE = InnoDB,
 PARTITION p2 VALUES LESS THAN (734683) ENGINE = InnoDB,
 PARTITION p3 VALUES LESS THAN MAXVALUE ENGINE = InnoDB) */

Essa situação de impasse acontece com frequência. Quero descobrir o que causa isso para evitar no futuro.

mysql innodb
  • 2 respostas
  • 3714 Views
Martin Hope
quanta
Asked: 2011-09-26 20:24:47 +0800 CST

Qual é a maneira mais segura de mudar o formato do log binário em tempo de execução?

  • 28

Devido ao seguinte aviso em mysqld.log:

[Aviso] Instrução não segura gravada no log binário usando o formato de instrução desde BINLOG_FORMAT = STATEMENT. A instrução não é segura porque usa uma cláusula LIMIT. Isso não é seguro porque o conjunto de linhas incluído não pode ser previsto.

Eu quero mudar o formato de replicação para MIXED.

Mas de acordo com o documento MySQL:

Alternar o formato de replicação em tempo de execução não é recomendado quando existem tabelas temporárias, porque as tabelas temporárias são registradas apenas ao usar a replicação baseada em instrução, enquanto na replicação baseada em linha elas não são registradas.

Então, a questão é como posso identificar se existem tabelas temporárias para alternar o formato de log binário com segurança?

mysql replication
  • 2 respostas
  • 50012 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve