[英]PHP and SQL display rows with same value
我在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();
}
當前結果
使用代碼計數器來組合輸出。 為了獲得最佳結果,我建議您首先在查詢中添加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>";
你在找這個嗎?
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
這里的例子如何合並兩行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.