查询SELECT *来自多个表

时间:2020-07-23 14:00:48

标签: php html mysql

我有两个看起来像这样的表:

发布表格:

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

荣誉表:

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

工作原理:我正在尝试向我的网站添加荣誉系统。我已经设置了上面显示的表格。每个用户都有自己的ident。当用户按下荣誉按钮时,用户的identphoto的ID将存储在荣誉表中,如下所示:

$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);
}

现在,我想显示每张照片的荣誉数量。目前,我只查询一个表,但是我还需要查询第二个表,以从该表中获取值。这就是我查询第一个表的方式:

<?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

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

从帖子p中选择p.id,p.photo,p.indent 左加入荣誉k on p.id = k.photo_id

答案 1 :(得分:-1)

也许您可以尝试联接表?

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;

这应该使您像:

post_id ... kudosCount

在此处阅读有关联接的更多信息: SQL joins

相关问题