How to differentiate data from two tables with columns of equal names in a SQL request with JOIN?

2

I've combined two tables with JOIN , the two tables have some columns with the same names ... When extracting data with PHP how will I differentiate?

Example :

foreach($dados as $values){    
    echo $values['price'];                  
}

How do I know if $ values ['price'] returns price from table ps_product or ps_product_attribute ?

    
asked by anonymous 07.12.2016 / 12:26

2 answers

5

SQL can stay:

SELECT pa.reference AS pa_reference, pa.price AS pa_price, p.reference AS p_reference FROM ps_product_attribute INNER JOIN ps_product ON p.id_product = pa.id_product LIMIT 0, 30;

Then in php you can access:

$values['pa_reference'];
$values['p_reference'];
$values['pa_price'];

In this way you define a 'alt name' of the columns for when I extract the results

    
07.12.2016 / 12:32
4

As php does not type the results columns with the same name have only the value of the last one. The solution is to add an alias to differentiate and get the values.

This can be done in two ways the first is to add the keyword AS after the original name of the column with the new name or just add the new name.

Change:

SELECT t1.campo1, t2.campo1 FROM t1 INNER JOIN t2 on t1.id = t2.id

To:

SELECT t1.campo1, t2.campo1 AS novocampo  FROM t1 INNER JOIN t2 on t1.id = t2.id
    
07.12.2016 / 12:31