简体   繁体   中英

Query SELECT * FROM multiple tables

I have two tables that looks like this:

Post table:

ID     |     photo      |   ident
-------------------------------------
80     |    img/photo1  |   ACH3882
81     |    img/photo2  |   SHD8837
82     |    img/photo3  |   SFF4837
83     |    img/photo4  |   DLL3266

Kudos table:

ID     |     photo_id   |   ident_id
-------------------------------------
1      |       80       |   SHD8837
2      |       83       |   ACH3882
3      |       82       |   SHD8837

How it works: I am trying to add kudos system to my website. I have already set up the tables like shows above. Each user has its own ident . When a user press the kudos button, the ident of the user and the id for the photo is stored in the kudos table, like this:

$id = $_GET['id']; // get id through query string
$ident = $_SESSION["ident"];

$sql = "INSERT INTO kudos (photo_id, ident_id) VALUES ('$id', '$ident')";
if(mysqli_query($link, $sql)){
    mysqli_close($link); // Close connection
    header("location:index.php"); // redirects to all records page
    exit;
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

Now I want to display the number of kudos given for each photo. Currently I only query one table, but I need to query the second one also to get the value from that table also. This is how I query the first table:

<?php
   $query = "SELECT * FROM post;
       if ($result = $mysqli->query($query)) {
              $num_rows = 0;
              while ($row = $result->fetch_assoc()) {
                  $num_rows++;
                  
                  
                  /* <!-- Feed start --> */
                  echo "{$row['photo']}.";
                  echo '<a class="btn" href="kudos.php?id=';
                  echo "{$row['id']}";
                  echo '">';
                  echo '★ Give kudos</a>';
                  echo ' 0';  <- This is where I want the number count of kudos gives to show up.
                  ... and so on

Can someone please help me out?

Select p.id,p.photo,p.indent from post p Left join kudos k on p.id = k.photo_id

Maybe you can try to join tables?

SELECT  Post.id as post, count(Kudos.ident_id) as kudos
FROM Post
LEFT JOIN Kudos ON Post.id=Kudos.photo_id  
GROUP BY Post.id;

This should return you smth like:

post_id ... kudosCount

Read more about joins here: SQL joins

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