【问题标题】:Duplication of results after selecting data from two tables with the same values从具有相同值的两个表中选择数据后结果重复
【发布时间】:2019-08-03 06:40:54
【问题描述】:

美好的一天!当我从两个具有相同值的表中选择数据时,我遇到了重复结果的问题。我的第一个表homepost 中有一个数据,ID 为2,我在表multiple 中有三个数据,ID 为2

所以。在我的源代码中。我正在选择具有相同值ID 的所有数据。但它复制了我来自homepost 的一个数据,因为我有来自multiple 的三个具有相同值[ID] 的数据。有什么帮助吗?谢谢!

例如下表:

Table [homepost]                    Table [multiple]

homeID   homeDesc               multipleID     multipleImage
2          John                     2              Image1
3        Samantha                   2              Image2
                                    2              Image3
                                    3              Image4
                                    3              Image5

我的代码结果:

John
Image1
John
Image2
John
Image3
Samantha
Image4
Samantha
Image5

我想要的是:

John
Image1
Image2
Image3

Samantha
Image4
Image5

这是我的源代码:

<?php
    include ("dbconnect.php");

    $content_sql="SELECT post.postID, post.postTitle, post.postDesc, post.postImage 
                    FROM post 
                        JOIN category ON (post.categoryID=category.categoryID) 
                    WHERE post.categoryID=".$_GET['categoryID'];

    if($content_query=mysqli_query($con, $content_sql)) {
        $content_rs=mysqli_fetch_assoc($content_query);
    }

do {
    echo $content_rs['postTitle'];
    echo $content_rs['postDesc'];
} while ($content_rs=mysqli_fetch_assoc($content_query))

?>

【问题讨论】:

标签: php sql join select duplicates


【解决方案1】:

您可以在每次循环时简单地检查名称,并且仅在它是新名称时才输出它

<?php
include ("dbconnect.php");

$sql="SELECT post.postID, post.postTitle, post.postDesc, post.postImage 
      FROM post 
          JOIN category ON (post.categoryID=category.categoryID) 
      WHERE post.categoryID=?";

$stmt = $con->prepare($sql);
$stmt->bind_param('i', $_GET['categoryID']);
$stmt->execute();

$result = $stmt->get_result();

$last_name = '';        
while ( $row = $result->fetch_assoc() ) {
    if ( $last_name != $row['postTitle'] ) {
        echo $row['postTitle'];
        $last_name = $row['postTitle'];
    }

    echo $row['postDesc'];
}
?>

【讨论】:

  • 我试过这个。这适用于postTitle。但是postDesc 不起作用,因为它与content_rs 相呼应,它说Unidentified Variable。有什么解决办法吗?我知道它会出错,因为没有变量 $content_rs 可以开始。
  • 再次检查代码。我还让它绑定了 $GET 参数
  • 没关系。我刚刚将$content_rs 更改为$row。它现在工作。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2018-07-09
  • 2012-01-22
  • 1970-01-01
  • 2010-09-29
  • 1970-01-01
  • 2020-01-03
  • 2016-09-29
  • 2018-10-20
相关资源
最近更新 更多