Doubt to build Mysql query

Asked

Viewed 59 times

0

In my system I have the following tables: tb_partida(id, data_hora, flag_ativo, tb_cotacao_id, tb_campeonato_id), tb_campeonato(id, nome_camp, tb_pais_id) e **tb_pais**(id, nome_pais, tb_continente_id).

Well, I need to popular one select with the country and championship matches and the value being the id of the championship onde tb_partida.flag_ativo = 1.
So far I have the following:

Function:

function seleciona_campeonatos_ativos()
{
    $link = conectar();

    $query = "SELECT tb_campeonato.id as id_campeonato, 
      tb_campeonato.nome_camp as nome_campeonato, 
      tb_pais.nome_pais as nome_pais
      FROM tb_campeonato, tb_pais
      WHERE tb_pais.id = tb_campeonato.tb_pais_id";

    $result = mysqli_query($link, $query) or die(mysqli_error($link));

    while ($registro = mysqli_fetch_assoc($result))
    {
        echo "<option value='".$registro['id_campeonato']."'>".$registro['nome_pais'].'» '.$registro['nome_campeonato']."</option>";
    }
}

Select:

<label for="sel1">Filtrar por campeonato:</label>
<br>
<div class="form-group">
    <select style="width: 300px;" class="form-control" id="sel1">
        <?php
            seleciona_campeonatos_ativos();
        ?>
    </select>
</div>

How do I show only the championships for which there is an active match?

  • 2

    Already tried to put at the end of the query "AND tb_start.flag_active = 1" ?

1 answer

0


Just like the dichrist commented, add the condition WHERE for the column flag_ativo:

SELECT 
    c.id AS id_campeonato, 
    c.nome_camp AS nome_campeonato, 
    p.nome_pais AS nome_pais
FROM 
    tb_campeonato c
LEFT JOIN  
    tb_pais p ON p.id = c.tb_pais_id
LEFT JOIN  
    tb_partida pt ON pt.tb_campeonato_id = c.id
WHERE 
    pt.flag_ativo = 1

See on sqlfiddle

  • I checked the script you suggested and received the following error: #1064 - You have an error in your SQL syntax; check the manual that Corresponds to your Mariadb server version for the right syntax to use near 'INNER JOIN tb_pais ON tb_pais.id = tb_campeonato.tb_pais_id FROM tb_campeonato ' at line 2

  • @Guilhermeramalho I fixed the code and added the example in sqlfiddle

  • Man, thank you so much for the answer. You’re really doing SELECT the way I wanted. But he selects the same championship twice and this will cause him to show the same country>>championship twice or as many times as he has a match that contains them. Is there any way I can limit it so that each country and championship only appears once?

  • Have yes, grouping the results, in the end add GROUP BY p.nome_pais

  • Thanks again, now yes it’s the way I wanted it.

Browser other questions tagged

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