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-21546

simplifiedDB's questions

Martin Hope
simplifiedDB
Asked: 2017-04-05 05:37:46 +0800 CST

Log_Slave_Updates no MySQL 5.7 falha na replicação no Linux?

  • 0

Eu tenho uma configuração de replicação mestre mestre no RHEL para 2 nós. Um servidor está atuando como mestre e escravo para outro servidor (que também é mestre e escravo) Digamos que um servidor e um servidor B

Habilitei log_slave_updates no servidor B para que todas as instruções recebidas do mestre (servidor A) sejam registradas nos logs binários do servidor B .

Eu estava esperando Replication , falhará porque:

         1. Created a Table on Server A.
         2. It get replicated to Server B.

Agora o log binário do escravo B irá para o servidor A e isso deve quebrar a replicação dizendo "tabela já existe". mas não

Qual é a lógica aqui?

Editar parte:

  1. ID do servidor em ambos os servidores são diferentes
mysql replication
  • 1 respostas
  • 261 Views
Martin Hope
simplifiedDB
Asked: 2015-11-27 02:51:28 +0800 CST

Tamanho do arquivo de log binário na replicação Mysql

  • 0

Eu tenho uma configuração de replicação de servidor mestre em servidores Linux.

Detalhes da configuração mestre:

 MySQL version is 5.1 and replication mode is MIXED type.

Detalhes da configuração do escravo:

 MySQL version is 5.6

Se eu inserir um único registro, ele será replicado para o escravo.

Quando estou executando um script para inserir milhares de registros no mestre, ele não está sendo replicado.

Quando vejo o tamanho do arquivo de log binário, é de 908 MB e quando vejo o tamanho do arquivo de log de retransmissão, é de 560 KB.

O tamanho de um arquivo de log binário é importante?
ou qual é a causa provável disso.

Abaixo estão os detalhes do cnf mestre:

  [mysqld]

  datadir=/var/lib/mysql
  socket=/var/lib/mysql/mysql.sock
  user=mysql
  # Disabling symbolic-links is recommended to prevent assorted security risks
    symbolic-links=0
    bind-address = #master IP# ( not showing here )
    port=3306
    wait_timeout=90
    net_read_timeout=90
    connect_timeout=90
    max_connections=100
    lower_case_table_names=1
    log-bin=mysql-bin
    binlog_format=MIXED
    server-id=1

[mysqld_safe]
     log-error=/var/log/mysqld.log
     pid-file=/var/run/mysqld/mysqld.pid
mysql replication
  • 1 respostas
  • 2749 Views
Martin Hope
simplifiedDB
Asked: 2015-08-18 02:51:05 +0800 CST

FLUSH TABLE: não é possível executar o comando fornecido porque você possui tabelas ativas bloqueadas mysql

  • 2

Se eu executar essas consultas uma a uma, todas falharão, exceto a primeira:

Consulta1:

flush table tablename1 with read lock;

Funciona

Consulta2:

flush table tablename2 with read lock;

Erro: não é possível executar o comando fornecido porque você possui tabelas ativas bloqueadas mysql

Se eu executar, da forma abaixo, funciona:

Consulta:

flush table tablename1,tablename2 with read lock;

O que está acontecendo lá dentro?

mysql mysql-5.6
  • 2 respostas
  • 7346 Views
Martin Hope
simplifiedDB
Asked: 2015-06-27 04:12:32 +0800 CST

Replicação de várias fontes em um único escravo com várias instâncias do MySQL

  • 0

eu tinha 1 instância do mysql 5.6 em um servidor A (Slave S)

1 Mysql instalado no servidor B (Master M1)

1 MySql instalado no servidor C ( Master M2 )

At Slave end :

I have created one more instance by creating one more my.conf file from existing my.cnf in Slave and placed it in "C:\Program Files (x86)\MySQL\MySQL Server 5.6\my.conf" which looks like this : 

 # MySQL Server Instance Configuration File
 # ----------------------------------------------------------------------
 # Generated by the MySQL Server Instance Configuration Wizard
 #
 #
 # Installation Instructions
 # ----------------------------------------------------------------------
 #
 # On Linux you can copy this file to /etc/my.cnf to set global options,
 # mysql-data-dir/my.cnf to set server-specific options
 # (@localstatedir@ for this installation) or to
 # ~/.my.cnf to set user-specific options.
 #
 # On Windows you should keep this file in the installation directory 
      # of your server (e.g. C:\Program Files\MySQL\MySQL Server X.Y). To
    # make sure the server reads the config file use the startup option 
 # "--defaults-file". 
 #
 # To run run the server from the command line, execute this in a 
 # command line shell, e.g.
 # mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server X.Y\my.ini"
 #
 # To install the server as a Windows service manually, execute this in a 
 # command line shell, e.g.
 # mysqld --install MySQLXY --defaults-file="C:\Program Files\MySQL\MySQL              Server X.Y\my.ini"
 #
 # And then execute this in a command line shell to start the server, e.g.
 # net start MySQLXY
 #
 #
 # Guildlines for editing this file
 # ----------------------------------------------------------------------
 #
 # In this file, you can use all long options that the program supports.
 # If you want to know the options a program supports, start the program
 # with the "--help" option. 
 #
 # More detailed information about the individual options can also be
 # found in the manual.
 #
 #
 # CLIENT SECTION
 # ----------------------------------------------------------------------
 #
 # The following options will be read by MySQL client applications.
 # Note that only client applications shipped by MySQL are guaranteed
 # to read this section. If you want your own MySQL client program to
 # honor these values, you need to specify it as an option during the
 # MySQL client library initialization.
 #
  [client]

     port=3306
     #ssl-ca=ca.pem
     #ssl-cert=client-cert.pem
     #ssl-key=client-key.pem

    [mysql]

      default-character-set=utf8


  # SERVER SECTION
  # ----------------------------------------------------------------------
  #
  # The following options will be read by the MySQL Server. Make sure that
  # you have installed the server correctly (see above) so it reads this 
  # file.
  #
[mysqld]
  server-id=1
  log-bin=mysql-bin
  binlog_format=ROW
  # The TCP/IP Port the MySQL Server will listen on
  port=3306

   innodb_file_per_table = 1
   innodb_file_format = barracuda
   max_allowed_packet = 256M
   innodb_lock_wait_timeout=120
   transaction-isolation = READ-COMMITTED
   interactive_timeout=300
   wait_timeout=300

 #Path to installation directory. All paths are usually resolved relative        to this.
   basedir="C:/Program Files (x86)/MySQL/MySQL Server 5.6/"

#Path to the database root
   datadir="C:/ProgramData/MySQL/MySQL Server 5.6/Data/"

# The default character set that will be used when a new schema or table is
# created and no character set is defined
   character-set-server=utf8

# The default storage engine that will be used when create new tables when
   default-storage-engine=INNODB

# The default storage engine that will be used for temporary tables
   default-tmp-storage-engine=INNODB

# Set the SQL mode to strict
   sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

# The maximum amount of concurrent sessions the MySQL server will
# allow. One of these connections will be reserved for a user with
# SUPER privileges to allow the administrator to login even if the
# connection limit has been reached.
 max_connections=1510

# Query cache is used to cache SELECT results and later return them
# without actual executing the same query once again. Having the query
# cache enabled may result in significant speed improvements, if your
# have a lot of identical queries and rarely changing tables. See the
# "Qcache_lowmem_prunes" status variable to check if the current value
# is high enough for your load.
# Note: In case your tables change very often or if your queries are
# textually different every time, the query cache may result in a
# slowdown instead of a performance improvement.
   query_cache_size=164M

# The number of open tables for all threads. Increasing this value
# increases the number of file descriptors that mysqld requires.
# Therefore you have to make sure to set the amount of open files
# allowed to at least 4096 in the variable "open-files-limit" in
# section [mysqld_safe]
    table_cache=3020

# Maximum size for internal (in-memory) temporary tables. If a table
# grows larger than this value, it is automatically converted to disk
# based table This limitation is for a single table. There can be many
# of them.
    tmp_table_size=30M


# How many threads we should keep in a cache for reuse. When a client
# disconnects, the client's threads are put in the cache if there aren't
# more than thread_cache_size threads from before.  This greatly reduces
# the amount of thread creations needed if you have a lot of new
# connections. (Normally this doesn't give a notable performance
# improvement if you have a good thread implementation.)
    thread_cache_size=64

#*** MyISAM Specific options

# The maximum size of the temporary file MySQL is allowed to use while
# recreating the index (during REPAIR, ALTER TABLE or LOAD DATA INFILE.
# If the file-size would be bigger than this, the index will be created
# through the key cache (which is slower).
     myisam_max_sort_file_size=100G

# If the temporary file used for fast index creation would be bigger
# than using the key cache by the amount specified here, then prefer the
# key cache method.  This is mainly used to force long character keys in
# large tables to use the slower key cache method to create the index.
      myisam_sort_buffer_size=30M

# Size of the Key Buffer, used to cache index blocks for MyISAM tables.
# Do not set it larger than 30% of your available memory, as some memory
# is also required by the OS to cache rows. Even if you're not using
# MyISAM tables, you should still set it to 8-64M as it will also be
# used for internal temporary disk tables.
      key_buffer_size=252M

# Size of the buffer used for doing full table scans of MyISAM tables.
# Allocated per thread, if a full scan is needed.
      read_buffer_size=64K
      read_rnd_buffer_size=256K

# This buffer is allocated when MySQL needs to rebuild the index in
# REPAIR, OPTIMZE, ALTER table statements as well as in LOAD DATA INFILE
# into an empty table. It is allocated per thread so be careful with
# large settings.
     sort_buffer_size=256K


#*** INNODB Specific options ***


# Use this option if you have a MySQL server with InnoDB support enabled
# but you do not plan to use it. This will save memory and disk space
# and speed up some things.
#skip-innodb

# Additional memory pool that is used by InnoDB to store metadata
# information.  If InnoDB requires more memory for this purpose it will
# start to allocate it from the OS.  As this is fast enough on most
# recent operating systems, you normally do not need to change this
# value. SHOW INNODB STATUS will display the current amount used.
    innodb_additional_mem_pool_size=11M

# If set to 1, InnoDB will flush (fsync) the transaction logs to the
# disk at each commit, which offers full ACID behavior. If you are
# willing to compromise this safety, and you are running small
# transactions, you may set this to 0 or 2 to reduce disk I/O to the
# logs. Value 0 means that the log is only written to the log file and
# the log file flushed to disk approximately once per second. Value 2
# means the log is written to the log file at each commit, but the log
# file is only flushed to disk approximately once per second.
    innodb_flush_log_at_trx_commit=1

# The size of the buffer InnoDB uses for buffering log data. As soon as
# it is full, InnoDB will have to flush it to disk. As it is flushed
# once per second anyway, it does not make sense to have it very large
# (even with long transactions).
     innodb_log_buffer_size=5M

# InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and
# row data. The bigger you set this the less disk I/O is needed to
# access data in tables. On a dedicated database server you may set this
# parameter up to 80% of the machine physical memory size. Do not set it
# too large, though, because competition of the physical memory may
# cause paging in the operating system.  Note that on 32bit systems you
# might be limited to 2-3.5G of user level memory per process, so do not 
# set it too high.
    innodb_buffer_pool_size=489M

# Size of each log file in a log group. You should set the combined size
# of log files to about 25%-100% of your buffer pool size to avoid
# unneeded buffer pool flush activity on log file overwrite. However,
# note that a larger logfile size will increase the time needed for the
# recovery process.
  innodb_log_file_size=98M

# Number of threads allowed inside the InnoDB kernel. The optimal value
# depends highly on the application, hardware as well as the OS
# scheduler properties. A too high value may lead to thread thrashing.
  innodb_thread_concurrency=8


 [mysqld1]

  basedir ="C:\Program Files (x86)\MySQL\MySQL Server 5.6"

  port = 3307

  enable-named-pipe

  socket = mypipe1


 [mysqld2]

   basedir ="C:\Program Files (x86)\MySQL\MySQL Server 5.6"

   port = 3308

   enable-named-pipe

   socket = mypipe2

Agora eu quero replicar M1 e M2 para os escravos. Como devo fazer isso?

windows replication
  • 1 respostas
  • 522 Views
Martin Hope
simplifiedDB
Asked: 2015-06-26 23:07:29 +0800 CST

Para várias instâncias do mysql, é necessário um novo download quando existe um?

  • 1

Eu preciso de várias instâncias do Mysql no mesmo servidor. Eu tinha passado por muitos links, mas fiquei confuso aqui:

What i have : MySQL 5.6 is already installed on my windows server A.
Installed at : "C:\Program Files (x86)\MySQL\MySQL_Server_5.6\"

Problem :   For multiple instances , do i need to download and install new mysql(either same or higher version) on server A ?

OR
  should i just copy existing my.conf file in new folder and then change its port number and then done.

Minha própria análise continua na nova instalação, mas por favor confirme.

windows mysql-5.6
  • 2 respostas
  • 804 Views
Martin Hope
simplifiedDB
Asked: 2015-06-02 23:41:56 +0800 CST

Replicação no mesmo servidor em diferentes bancos de dados. Mysql 5.6

  • 3

O que eu tenho :

  • uma máquina Windows com uma instância do MySQL 5.6 Server.
  • dois bancos de dados chamados test e test2.
  • Testbanco de dados tem uma tabela chamada activitycom colunas ideclass

O que eu preciso :

  • replicação de test.activitytabela para test2banco de dados com uma condição que Test.activity.class = 'B'.

Eu sei como replicar em um servidor diferente. Mas não para o mesmo servidor em bancos de dados diferentes. Verifiquei este link , mas não fornece informações suficientes.

mysql replication
  • 5 respostas
  • 6439 Views
Martin Hope
simplifiedDB
Asked: 2014-09-17 05:41:14 +0800 CST

Atualize registros específicos da tabela com base na saída da subconsulta (sql server)

  • 0

tem esta consulta que produz a saída abaixo:

select sec.site,sec.Name,sec.Freq from
( select Name from sec group by name having count(Freq) > 3)as dt
inner join sec on dt.Name = sec.Name
where sec.Freq like '%MUF2900%' ;


site    Name            Freq
S003   sct003a       MUF2900_26
S003   sct003a       MUF2900_26 
S003   sct003a       MUF2900_26
S034   sct034a       MUF2900_26
S034   sct034a       MUF2900_26
S034   sct034a       MUF2900_26

Agora eu tenho que atualizar meu outro teste de nome de tabela com base na saída da consulta acima. O teste de tabela atualmente contém os seguintes registros (antes da atualização):

 site      cell       ID
 S003      09M00011   1019581
 S003      09M00012   1019582
 S003      09M00013   1019583
 S003      29M00011   1019581
 S003      29M00012   1019582
 S003      29M00013   1019583
 S034      09M00011   1016581
 S034      09M00011   1016582
 S034      09M00011   1016583

 now for site S003 , ID for for cell starting from 09 and 29 are same ,so i need to update the ID for 29  i.e the unit place of ID should be incremented by 10 , like following..

REQUERIDOS :

  Site      cell       ID
 S003      09M00011   1019581
 S003      09M00012   1019582
 S003      09M00013   1019583
 S003      29M00011   10195811
 S003      29M00012   10195812
 S003      29M00013   10195813
 S034      09M00011   1016581
 S034      09M00011   1016582
 S034      09M00011   1016583

Eu tenho muitos registros como este.

Nota: S034 não possui célula a partir de 29, portanto seu ID não precisa ser atualizado.

o que eu tentei e onde estou ficando confuso é:

 update Test set ID = (how to do this ??)
  where Test.site = (select sec.site,sec.Name,sec.Freq from
( select Name from sec group by Name having count(Freq) > 3)as dt
inner join sec on dt.Name = Sec.Name
where sec.Freq like '%MUF2900%') where cell like '29M%';

Como devo fazer isso. Preciso fazer cursor para isso ??

sql-server t-sql
  • 2 respostas
  • 655 Views
Martin Hope
simplifiedDB
Asked: 2014-09-02 12:50:16 +0800 CST

Inserindo dados com base em diferentes condições

  • -4

Embora, eu me esforcei para tornar a pergunta fácil de entender, mas ainda não sei o que está errado. De qualquer forma, estou tentando torná-lo mais compacto

Eu tenho a tabela abaixo agora apenas:

Na coluna número JU significa Junior e SU significa Senior

 name         number            fin
------------------------------------
 paul        JU00011          100401
 paul        JU00012          100402
 paul        JU00012          100403
 maul        JU00021          100641
 maul        JU00022          100642
 paul        SU00012          100401
 paul        SU00012          100402
 paul        SU00012          100403

Now in this table , fin for paul are same ( for junior ans senior ).
i need to make an update in this table 
for example :If paul is coming under two numbers (i.e JU and SU) and have same fin number,
so i want to update fin , when 2 fin are same and belongs to same name and is coming under Junior category and Senior Category 

 Final Result :
name         number            fin
------------------------------------
 paul        JU00011          100401
 paul        JU00012          100402
 paul        JU00012          100403
 maul        JU00021          100641
 maul        JU00022          100642
 paul        SU00012          1004011
 paul        SU00012          1004012
 paul        SU00012          1004013

  Such type of records are more.
sql-server t-sql
  • 2 respostas
  • 123 Views
Martin Hope
simplifiedDB
Asked: 2014-01-09 23:19:04 +0800 CST

coluna atualizada automaticamente após 24 horas no mysql

  • 3

eu tenho uma tabela T1 com coluna:

Name      State             time
mon         1          2014-01-09 11:23:00
tue         0          2014-01-07 14:40:00
wed         2          2014-01-08 09:23:00 
thu         0          2014-01-09 12:23:00   

Agora eu quero agendar um evento ou desenvolver um gatilho (se possível), se algum estado for 0/2 e seu horário for superior a 24 horas do horário atual, ele deverá ser atualizado para 1.

Por exemplo, na tabela acima, o estado de ter é 0 e o tempo é superior a 24 horas , portanto, o estado deve ser atualizado para 1 e o mesmo se aplica a wed , mas não a qui.

Passei por muitas perguntas como:

https://stackoverflow.com/questions/17387802/how-to-auto-update-mysql-after-timestamp-field-expierd

https://stackoverflow.com/questions/12421756/how-to-update-table-after-a-certain-time-interval

mas ainda não entendi, como resolver meu problema

mysql mysql-5.5
  • 1 respostas
  • 34310 Views
Martin Hope
simplifiedDB
Asked: 2013-12-07 00:41:01 +0800 CST

Aviso antes de emitir o comando delete/update em mysql/oracle e, em seguida, executa

  • 0

Existe algum utilitário / função no mysql / oracle que impeça que eu emita algum comando de exclusão/atualização incorretamente, uma mensagem deve ser exibida em command_line* (se possível no ubuntu) perguntando se "você tem certeza de executar este comando", se sim, exclua O comando /update será executado?

Eu pesquisei isso, mas nenhuma solução específica é fornecida para isso. Eu tentei SOURCE também, mas não é exatamente o que eu quero.

Alguém tem alguma ideia sobre isso?

Se estou prestes a disparar o comando de atualização em > 100.000 registros, deve aparecer um prompt perguntando "você realmente deseja executar?", como no Unix, se usarmos rm filename, ele pergunta se você tem certeza de que deseja excluir ?

mysql oracle
  • 2 respostas
  • 2047 Views
Martin Hope
simplifiedDB
Asked: 2013-12-04 03:44:14 +0800 CST

adição na coluna datetime durante a inserção no mysql

  • 1

Eu tenho uma tabela com menos de 5 colunas..timestamp é o tipo de dados para a coluna relacionada a timedate:

 Region     event_time     start_time     mid_time   end_time
 India   2013-11-03 13:00:00        
 America
 Holland
Switzerland    

Eu tenho uma fonte de onde os dados da coluna acima estão vindo em um intervalo específico... agora, durante a inserção, preciso adicionar tempo.

Por ex. se no arquivo csv eu tiver event_time de 2013-11-03 13:00:00, então para a Índia o tempo será adicionado às 5:30 (devido ao GMT) antes da inserção... e os valores finais inseridos devem ser 2013-11-03 18 :30:00..o mesmo se aplica ao resto das regiões e colunas de data e hora..como devo fazer isso...também o horário de verão incluirá para outras regiões que têm isso

Eu tentei funções adddate, addtime... mas isso não funciona... eu tentei atualizar após a inserção, mas esta não é uma solução que eu quero... alguma ajuda??

mysql-5.5
  • 1 respostas
  • 200 Views
Martin Hope
simplifiedDB
Asked: 2013-11-19 05:29:54 +0800 CST

Diferença de data e hora no MySQL quando o formato é Varchar

  • 1

Tenho duas colunas em uma tabela: STOPe START, do tipo varchar.

Eu quero ter a diferença entre as duas colunas e estou usando:

SELECT DATEDIFF(stop, start) AS difference from T1;

Está me dando null, por causa de diferentes tipos de dados.

Para testar, também tentei:

SELECT STR_TO_DATE('5/16/2011 20:14 PM', '%c %e %Y %H:%i:%s');

Também é dar null.

O que devo fazer pela diferença? Eu tenho nnúmero de dados e tempo em diferentes formatos.

insira a descrição da imagem aqui

mysql mysql-5.5
  • 1 respostas
  • 2198 Views
Martin Hope
simplifiedDB
Asked: 2013-10-19 05:55:33 +0800 CST

Procedimento e Automação no Mysql

  • 0

Eu tenho uma tabela com essas colunas e os valores vêm dessas tabelas de um arquivo csv em um intervalo regular de n minutos (por cron o comando load infile):

 ID (PK)        status      first      last     value
 1                Q          12         15       low
 2                Q          12         15       low
 3                O          12         15       High

agora, sempre que os próximos dados vierem, ele deve primeiro verificar se o ID está presente na tabela, se estiver, basta atualizar o campo correspondente desse ID e, se vier um novo ID, basta inserir os dados.

Para isso criei um procedimento:

     create procedure test.testproc (IN no int , IN status varchar(10))     
     begin if exists (select id from test.testproc where id = no)
     then 
     update baseline set status=status where id=no;
     else insert into  tname(id,status) value(no,status);
     end if;
     end$$

Agora o que eu quero saber:

  1. devo criar duas tabelas para isso, ou seja, uma é uma tabela temporária e uma tabela principal? ** estou 100% confuso aqui o que devo fazer aqui

  2. como devo automatizar todos esses, ou seja, os dados vêm de um arquivo csv, então meu script de carga infile é executado, então meu procedimento acima deve ser executado e verificar se o ID já está presente, ele simplesmente será atualizado, senão ele será inserido.

OU, se você tiver qualquer outro processo, informe

mysql stored-procedures
  • 1 respostas
  • 403 Views
Martin Hope
simplifiedDB
Asked: 2013-09-19 02:52:26 +0800 CST

recuperar dados com base em uma condição

  • 0

Eu tenho 2 tabelas TAe TB:

TA
--------
id  name
1   a
2   b
3   c
4   d
5   e
6   f

TB
--------
id  p_id  name
1   1     a
2   1     b
3   1     c
4   2     a
5   2     b
6   2     d

Eu preciso: se p_id = 1então:

id  name match
1   a    1 
2   b    1
3   c    1
4   d    0
5   e    0
6   f    0

Se p_id = 2então:

id  name match
1   a    1 
2   b    1
3   c    0
4   d    1
5   e    0
6   f    0
mysql oracle
  • 1 respostas
  • 562 Views
Martin Hope
simplifiedDB
Asked: 2013-09-18 00:15:15 +0800 CST

como o auto_increment funciona no mysql

  • 1

Estou confuso aqui, crio uma tabela e tenho 2 colunas de id e nome.

Agora id é chave primária, não null e incremento automático.

Suponha que eu dispare:insert into table (name) values('test');

isso vai me dar:

1  | test

Agora se eu disparar:alter table table_name auto_increment = 5;

isso preencherá o id com 5 na próxima inserção.

agora, se eu excluir o valor de id = 5 e inserir novamente:insert into table (name) values ('test2');

isso me dá:

 6  | test2

por que não me dá 5 de novo?

Também não é possível que não possamos redefinir os valores auto_increment existentes para o desejado no MySql?

mysql-5.5
  • 1 respostas
  • 1192 Views
Martin Hope
simplifiedDB
Asked: 2013-09-06 22:14:16 +0800 CST

junções internas com a cláusula where para nenhum valor?

  • 1

Tenho 2 tabelas:

Tabela 1

Pai (varchar) Filho (varchar)

Mesa 2

C1(varchar) PC (varchar)

Dados de amostra:

insira a descrição da imagem aqui

Requisito - Preciso dos valores Table2.C1 para os quais a coluna Table2.PC = Table1.Child , mas os valores Child devem ser diferentes dos valores Table1.Parent.

Estou usando a consulta abaixo no mysql:

select distinct(C1),Child,PC 
  from Table2 inner join Table1 
    on Table2.PC=Table1.Child 
 where Table1.Child not in (select Parent from Table1);

Está dando um conjunto vazio, mas há valores em Child que são iguais aos de PC, mas não em Parent....

Onde estou errando?

mysql join
  • 3 respostas
  • 4012 Views
Martin Hope
simplifiedDB
Asked: 2013-07-12 03:58:04 +0800 CST

Precisa encontrar o número de funcionários que não estão em todos os departamentos

  • 0

eu tenho uma tabela T1 que tem duas colunas empname,department

todo emp deve estar em 37 departamentos, mas há alguns funcionários que estão em menos de 37 departamentos.

Preciso encontrar os nomes dos emp que não estão em todos os 37 departamentos.

Estou usando uma consulta:

select empname from T1 having count (department) < 37;

mas não está me dando a saída desejada.

mysql group-by
  • 1 respostas
  • 946 Views
Martin Hope
simplifiedDB
Asked: 2013-05-29 22:58:24 +0800 CST

Atualizando uma coluna após a expiração de um tempo específico no MySQL

  • 3
  1. Eu tenho uma tabela onde tenho uma coluna chamada state(int(2))e modify_time( time_stampna atualização do timestamp atual).

  2. Eu tenho um gatilho de atualização que altera o valor da coluna de estado com 0base em alguma condição.

  3. Desejo definir o valor da statecoluna para 1após 24 horas modify_time, se ainda estiver 0.

  4. Eu tentei o método abaixo para testar:

    CREATE EVENT myevent1 
     ON SCHEDULE AT current_timestamp + interval 1 minute 
     DO UPDATE test.mytabletable SET state = 0;
    

Isso não fez nada. Existe algum método alternativo?

mysql trigger
  • 2 respostas
  • 18121 Views
Martin Hope
simplifiedDB
Asked: 2013-05-06 23:25:32 +0800 CST

O gatilho não é executado quando o valor de uma coluna muda de nulo para 1

  • 4

Eu tenho este gatilho:

delimiter $$

create trigger tr 
after update on t1
for each row
begin

  if new.col1 !=old.col1 
    then update t2 set col2 =1 where t2.col3=t1.col3;
  end if;

end

$$

Este gatilho funciona quando col1o valor de muda de 0 para 1, mas quando muda de nulo para 1, o gatilho não faz nenhuma alteração em t2.

Eu só queria saber porque é assim. Sei que null é diferente, mas estou apenas comparando os valores.

Eu resolvi meu problema fazendo new.col1 =1.

mysql datatypes
  • 4 respostas
  • 7704 Views
Martin Hope
simplifiedDB
Asked: 2013-04-26 23:35:27 +0800 CST

É possível que um gatilho atualize uma linha em uma tabela usando um valor que foi excluído?

  • 1

Eu tenho um gatilho que está atualizando uma coluna em uma tabela diferente após a inserção da linha:

mysql>delimiter $$

mysql> create trigger status

 after insert on table2

 FOR EACH ROW 

 BEGIN update

 table1 inner join table2

 ON table1.id=table2.id 

 set table1.state=0 ;

Agora quero redefinir table1.state=1sempre que o mesmo valor for excluído. Isso é possível?

mysql trigger
  • 1 respostas
  • 10186 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