Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
MySQL> Getting table name along with SELECT output

We have some legacy tables with very similar structure. These tables were kept separate because the format of the same information was slightly different, depending upon the source from where the information was scraped [don't shoot the schema inheritor;)]. We have been using UNION in our queries.

For example:

SELECT a, b, c, FROM Table_1 WHERE …
UNION
SELECT a, b, c, FROM Table_2 WHERE …
UNION
SELECT a, b, c, FROM Table_3 WHERE …

This kludgy arrangement has been working but we would like to know which table a piece of information in our output is coming from. Is there some way to realize that?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Just add a column to each subquery that contains the table name:

SELECT 'Table_1' tablename, a, b, c, FROM Table_1 WHERE ...
UNION ALL
SELECT 'Table_2', a, b, c, FROM Table_2 WHERE ...
UNION ALL
SELECT 'Table_3', a, b, c, FROM Table_3 WHERE ...

Note that I changed the UNIONs to UNION ALLs, since adding this column basically defeats the deduplication functionality that UNION provides.

over 4 years ago · Santiago Trujillo Relatório

0

You can do:

SELECT 'Table_1' as source, a, b, c, FROM Table_1 WHERE …
UNION ALL
SELECT 'Table_2', a, b, c, FROM Table_2 WHERE …
UNION ALL
SELECT 'Table_3', a, b, c, FROM Table_3 WHERE …

And don't forget to use UNION ALL instead of UNION. It has better performance and doesn't remove rows.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda