简体   繁体   中英

For each SQL result, another SQL query? in PHP

I need help at getting data from MySQL Database. Right now I have a query that gives me:

Tournament ID

Tournament Name

Tournament Entry fee

Tournament Start and End date

For tournaments I am registered in. Now I want, for each tournament I am registered in, to count how many users are in that tournament, my points in that tournament , etc.

That info is in table called 'ladder'

ladder.id

ladder.points

ladder.userFK

ladder.tournamentFK

Database: http://prntscr.com/99fju1

PHP CODE for displaying tournaments I am registered in:

<?php
include('config.php');
$sql = "SELECT distinct tournaments.idtournament, tournaments.name, tournaments.entryfee, tournaments.start, tournaments.end
                from tournaments join ladder
                on tournaments.idtournament= ladder.tournamentFK and ladder.userFK=".$_SESSION['userid']."
                group by tournaments.idtournament";

$result = $conn->query($sql);               
    if($result->num_rows > 0){
        while($row = $result->fetch_assoc()) {                      
            $tournament="<li class='registered' data-id=".$row['idtournament']." data-entryfee=".$row['entryfee']." data-prize=".$tournamentPrize."><span class='name'>".$row['name']."</span><span class='entry-fee'>Entry fee: ".$row['entryfee']."&euro;</span><span class='prize-pool'>Prize pool: &euro;</span><span class='date-end'>".$row['start']."-".$row['end']."</span><span class='btns'><button>Standings</button></span></li>";
            echo $tournament;
        }                   
    }
$conn->close();
?>

Usually you can combine JOIN, COUNT() and GROUP BY in your query.

Some examples: MySQL joins and COUNT(*) from another table

This would be the query I think.Change column and table name if its not correct. Not tested but I am sure this will give you some idea to make required query

select count(ladder.tournamentId)as userCount,tournaments.name 
    from 
     ladder left join tournaments 
      on ladder.tournamentId =  tournaments.id 
       where ladder.tournamentId in 
         (
         select tournaments.id from 
           tournaments left join ladder 
            on ladder.tournamentId =  tournaments.id 
             where  ladder.userId='yourId'
          ) and ladder.userId <> 'yourId'
            group by ladder.tournamentId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM