我有两个表,即抽象表和具有一对多关系的作者,对于while循环上的每次迭代,我想显示抽象表中唯一数据行的html表,以及作者表中的相应行。
这就是我所做的:
public function getAll() {
try {
$sql = " SELECT tbl_abstract.abstract_id, tbl_abstract.first_name,
tbl_abstract.last_name,tbl_abstract.content,
tbl_author.afirst_name, tbl_author.alast_name,
tbl_author.aaffilition
FROM tbl_abstract
INNER JOIN tbl_author ON tbl_abstract.abstract_id = tbl_author.abstract_id
GROUP BY tbl_abstract.abstract_id";
$stmt= $this->pdo->prepare($sql);
$stmt->execute();
$count = $stmt ->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
<table class="table" >
<tr>
<td align="center" >
//data from tbl_abstract
<?php echo $row["abstract_id"]; ?>. <?php print($row["abstract_title"]); ?>
<?php echo $row["first_name"].' '.$row["last_name"]; ?>,
//data from tbl_author
<?php echo $row["afirst_name"].' '.$row["alast_name"];?>
</td>
</tr>
<tr>
<td align="center" ">
//data from tbl_abstract
<?php print($row["content"]); ?>
</td>
</tr>
</table>
<?php
}
}catch(PDOException $e){
echo $e->getMessage();
return false;
}
}
tbl_author中有3条记录与tbl_abstract中的abstract_id相关联,但我只得到一条记录,而不是3条。请帮助
答案 0 :(得分:0)
尝试像这样删除GROUP BY
子句:
SELECT
tbl_abstract.abstract_id, tbl_abstract.first_name,
tbl_abstract.last_name,tbl_abstract.content, tbl_author.afirst_name,
tbl_author.alast_name, tbl_author.aaffilition
FROM
tbl_abstract
INNER JOIN
tbl_author ON tbl_abstract.abstract_id = tbl_author.abstract_id
Group by会将所有作者按abstract_id字段分组,这意味着它不会返回所有作者,而是仅返回一个作者的一个abstract_id(基于排序字段,在这种情况下可能是主键) ,因为未明确定义)。
答案 1 :(得分:0)
试试这个:-
<?php
$sql = "SELECT *
FROM tbl_abstract
where abstract_id IN (SELECT distinct abstract_id
FROM tbl_abstract)";
$stmt= $this->pdo->prepare($sql);
$stmt->execute();
$count = $stmt ->rowCount();
?>
<table class="table" >
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td align="center" >
//data from tbl_abstract
<?php echo $row["abstract_id"]; ?> <?php print($row["abstract_title"]); ?>
<?php echo $row["first_name"].' '.$row["last_name"]; ?>,
<?php
$sql1 = "SELECT *
FROM tbl_author
WHERE abstract_id = '".$row["abstract_id"]."'" ;
$stmt1= $this->pdo->prepare($sql1);
$stmt1->execute();
while($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)){
//data from tbl_author
echo $row1["afirst_name"].' '.$row1["alast_name"];
} ?>
</td>
<td align="center">
//data from tbl_abstract
<?php print($row["content"]); ?>
</td>
</tr>
<?php } ?>
</table>