How to do SELECT to get data in different tables and with different id's

0

It has 3 tables

    In the entrada table you have the data: id_entrada , id_empresa , id_categoria and id_subcategory.

  • In the cat_entradas table I have: id_categoria and categoria .

  • And in the sub_cate_entrada table I have: id_subcategoria and subcategoria .

I've already got the two ids (category_id and sub_subcategory) in the input table.

Now, I need to get the category and the subcategory in their respective tables. How can I do this in a SQL statement only, or will I have to do 2, one for each table?

    <?php
    $pdo = conectar();
    $this->dataConta=$pdo->prepare("SELECT categoria, subcategoria FROM entrada WHERE id_entrada=:id_entrada AND id_empresa=:id_empresa"); 
    $this->dataConta->bindValue(":id_entrada", 30); 
    $this->dataConta->bindValue(":id_empresa", 1); 
    $this->dataConta->execute(); 
    $res = $this->dataConta->fetch(PDO::FETCH_ASSOC);
    echo $res['categoria']." - ". $res['subcategoria'];
    $pdo = null;
    
asked by anonymous 29.10.2015 / 21:17

1 answer

2

You can use two inner joins, a single query returns all the results you need:

$resultado = $pdo->query(
    "SELECT e.id_categoria, e.id_subcategoria, c.categoria, s.subcategoria
    FROM entrada e
    INNER JOIN cat_entradas c ON c.id_categoria  = e.id_categoria
    INNER JOIN sub_cate_entrada s ON s.id_subcategoria = e.id_subcategoria"
);
while ($r = $resultado->fetch(PDO::FETCH_ASSOC)) {
    echo $r['id_categoria'] . ': ' . $r['categoria'] . '; ' . $r['id_subcategoria '] . ': ' . $r['subcategoria'] . '#';
}

This reads fields from multiple tables at the same time. The letters "e", "c" and "s" are aliases for the tables.

The example prints values for each line read.

    
29.10.2015 / 23:19