简体   繁体   中英

sql-php — i can't get the correct query to display the correct row from database

I have 2 tables in my database named user_logs and files and I want to match the fileId from files to the fileId in user_logs . I have correctly done that using this query

SELECT *, IF(t.cnt IS NULL, 0, t.cnt) AS c
FROM files LEFT JOIN
(SELECT count(*) AS cnt, fileId , schoolName FROM user_logs GROUP BY fileId) AS t
ON files.fileId = t.fileId
ORDER BY fileName DESC

Now, I want the schoolName row from user_logs to match it with schoolName from the other table named sample . And i want it to display the schoolName from user_logs (the schoools that clicked the file) and display the same row from files (the schools that not yet clicked the file)

I can't understand what i've researched. Here's my code.

<?php 

$sql = "SELECT *, IF(t.cnt IS NULL, 0, t.cnt) AS c
FROM files LEFT JOIN
(SELECT count(*) AS cnt, fileId , schoolName FROM user_logs GROUP BY fileId) AS t
ON files.fileId = t.fileId
ORDER BY fileName DESC";


    $result = mysqli_query($con,$sql);
    while ($row = mysqli_fetch_assoc($result)) {
    $fileId = $row['fileId'];
            $num_row = $row['c'];
        echo "<tr>";
            echo "<td>".$row['fileName']."</td>";
            echo "<td><a data-toggle='modal' href='#".$row['fileId']."'>". $num_row ." / 2 Schools Clicked</a></td>";      
        echo "</tr>";

        echo '<div class="modal fade" role="dialog" id="'.$row['fileId'].'">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">'. $row['fileName'] .'</h4>
      </div>
      <div class="modal-body">';
      // Here I want to display the schools that clicked the file from use_logs
      echo '<p>Name of schools that clicked the file :</p>
            <ul>
                <li>'.$row['schoolName'].'</li> 
            <ul>';
       // And here i want to display the school names that doesn't clicked the file yet
       echo '<p>Name of schools that doesn`t clicked the file yet:</p>
            <ul>
                <li>'.$row['schoolName'].'</li> 
            <ul>';
        echo '</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>';
}

 ?>

这个查询怎么样

SELECT COUNT(user_logs.id) as cnt, user_logs.schoolName From user_logs INNER JOIN files ON files.fileId = user_logs.fileId GROUP BY fileId ORDER  BY filename DESC

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