How to assign a single nickname to 2 columns of different tables?

Asked

Viewed 301 times

2

Is there any way to assign a nickname in 2 columns of different tables in SELECT?

SELECT
(a.coluna1, b.coluna2) as coluna_geral
FROM
tabela1 a
LEFT JOIN tabela2 b ...
  • I don’t know what you need it for, but you can’t do that. It was easier if you explain what you want to do with it...

  • Doing this doesn’t make much sense... if you return an id and b returns another id, you will end up getting lost..

  • an ALIAS is like an id can’t be repeated

  • In case I have a LEFTJOIN below where there is a table with similar columns, I wanted to centralize the data without having to do in php

  • Centralize as well as so?

  • You have to pick up one column at a time, you have no choice.

Show 1 more comment

1 answer

1

What you’re trying to do has no logic to the programming. If you have two different dice in two columns, giving them the same name will cause you to lose the reference of one of the two. For example:

SELECT
  a.coluna, b.coluna
FROM
tabela1 a
LEFT JOIN tabela2 b ...

 _________________
| coluna | coluna |
|--------|--------|
| NT     | 554    |
|________|________|

The result may be NT or 554 and has a 50% chance of not being what you want.

What is common happens, is columns with the same name have the same data, for example:

SELECT
  *
FROM
  compras a
     LEFT JOIN usuarios b ON b.userid = a.userid
[...]

 _________________
| userid | userid |
|--------|--------|
| 12     | 12     |
|________|________|

In this case it is good to omit one of the columns:

SELECT
  a.*, b.nome, b.cpf, b.etc
FROM
  compras a
     LEFT JOIN usuarios b ON b.userid = a.userid
[...]

So you already have the user id in the table compras and the rest of the table data usuarios.

If you want to print the data of two columns as one, the path is to concatenate them:

SELECT 
  CONCAT(a.coluna, '-', b.coluna) as coluna
FROM
tabela1 a
LEFT JOIN tabela2 b ...

 ________
| coluna |
|--------|
| NT-554 |
|________|

Browser other questions tagged

You are not signed in. Login or sign up in order to post.