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

Asked

Viewed 828 times

2

inserir a descrição da imagem aqui

I combined record of two tables using JOIN, the two tables have some columns with equal names... When extracting data with PHP how will I differentiate ?

Example :

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

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

  • 1

    @Miguel what would be the need (in this case) to put the two tables in full?

  • Naming columns does not solve? for example: ...PA.PRICE 'attr_price', P.PRICE 'prod_price'...

  • @We can make it happen ALIAS with the names of thebes ?

  • @jbueno what’s wrong with the question I asked ?

  • 1

    "requisition" or "requisition"?

  • @Andrépka Avoid posting code as image.

  • 1

    @jbueno is not a code, but a screenshot of a specific case...!!

Show 3 more comments

2 answers

5

The 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'];

This way sets an 'alias' of the columns for when I extract the results

4

Since php does not type the column results with the same name has only the value of the last one. The solution is to add an alias to differentiate and obtain the values.

This can be done in two ways the first is to add the keyword AS after the original column name 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

Browser other questions tagged

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