我在SQL中有两个表http://www.sqlfiddle.com/#!2/1f1fb/2
查询获取所有必需的信息。问题是我想显示这样的信息(期望的最终结果):
一些PHP代码:(如果查询有问题,对查询的修改是好的)
try{
$db=new readPDO('username');
$sql="
SELECT test.SAME, test.Nationality, test.Name, test2.Job
FROM test
LEFT JOIN test2
ON test.noID=test2.noID;
";
$statement=$db->prepare($sql);
$statement->execute();
if($statement->rowCount())
{
print"
<table width='280' border='1'>
";
while ($selector = $statement->fetch(PDO::FETCH_ASSOC))
print"<tr><td>$selector[SAME]</td></tr>";
print"
</table>
";
}
else
print"Error";
} catch(PDOException $e)
{
echo $e->getMessage();
}
目前的结果
答案 0 :(得分:0)
使用代码计数器来组合输出。为了获得最佳效果,建议您先在查询中添加order by
。
SELECT test.SAME, test.Nationality, test.Name, test2.Job
FROM test
LEFT JOIN test2
ON test.noID=test2.noID
order by test.SAME asc
;
然后在PHP while循环中使用计数器来计算要应用的rowspan
。
$rowspanCounter = 1;
$_same = '';
while ($selector = $statement->fetch(PDO::FETCH_ASSOC)){
if($_same == $selector[SAME]){
$rowspanCounter++;
}
else{
$_same = $selector[SAME];
$table_string .= "<tr><td rowspan=".$rowspan.">$selector[SAME]</td>";
$rowspanCounter = 1;
}
....//rest of the rows here.
print"</tr>";
}
//outside the while loop
print "</table>";
答案 1 :(得分:0)
SELECT test.SAME , test.Nationality, test.Name, coalesce(test2.Job,'')jobb
FROM test
LEFT JOIN test2
ON test.noID=test2.noID
group by SAME , name
order by same desc
此处示例如何merge two rows