Select two columns with the same name from two different tables


If I have two tables that have a column called direccion , and I want to take only one of them as I do?


Client table: ID, address, level, mail, password, name


Company table: EID, address, name

What I want to do is:

SELECT ID, direccion, nivel FROM cliente, empresa WHERE ID = 1;

The result I get is that the column direccion is ambiguous.

asked by Pavlo B. 12.01.2017 в 17:13

4 answers


You set an alias of the tables, and you get the field you want from each table:

SELECT a.dato, b.dato FROM tabla1 a, tabla2 b

If you want only the value of the field in table1:

SELECT a.dato FROM tabla1 a, tabla2 b

or if you want only the value of the field in table2:

SELECT b.dato FROM tabla1 a, tabla2 b

Based on your question, if you wish to obtain the address field only from the client table, it would be:

SELECT ID, cliente.direccion, nivel FROM cliente, empresa WHERE ID = 1;

or otherwise:

SELECT ID, a.direccion, nivel FROM cliente a, empresa b WHERE ID = 1;
answered by 12.01.2017 / 17:16

I imagine that you mean to make a selection of both tables but only show the field direccion of one of them. Use aliases and set which field you want to show

SELECT t1.direccion, t1.campo2, t2.campo3
FROM tabla1 t1, tabla2 t2
WHERE = t2.tabla1_id

This is an example of how you can do it.

answered by 12.01.2017 в 17:17

I think what you want to do is the following,

a.direccion AS cliente_direccion,
b.direccion AS empresa_direccion,
a.nombre AS cliente_nombre,
b.nombre AS empresa_nombre
FROM cliente AS a, empresa AS b 
answered by 12.01.2017 в 18:20

The way to do it is:

SELECT cliente.ID AS ID_Cliente, cliente.direccion AS Direccion_del_Cliente, empresa.direccion Direccion_de_la_Empresa, cliente.nivel AS Cliente_Nivel FROM cliente, empresa WHERE ID = 1 AND empresa.EID = 2 

The Aliases are NOT necessary, but allow you to identify in the columns of the query which table belongs to each one, otherwise, it would show you: "Address" and you would not know which table it refers to.

I made the query about the ID of the Client "Y" the EID of the company 2. If you do not place any EID of the company, it will throw you (in this way) ALL the addresses of the "company" table while it will always show you the same record of the "customer" table (the number 1).

answered by 12.01.2017 в 20:14