我有以下情况:
Site_A Link_AB Site_B Link_BC Site_C
001 001-002 002 002-003 003
001 001-002 002 002-004 004
001 001-005 005 005-006 006
我希望将其显示为:
001 001-002 002 002-003 003
002-004 004
001-005 005 005-006 006
有可能吗?
由于
答案 0 :(得分:0)
尽管在MySQL中可行,但这种类型的处理通常在表示层中完成。为什么?结果集的含义完全取决于行的顺序,SQL通常使用无序集。
因此,如果您有一个返回表的查询,您可以执行某些操作。可能最简单的方法是使用变量:
select if(@sa = Site_A, '', if(@sa := Site_A, @sa, @sa)) as Site_A,
if(@l = Link_AB, '', if(@l := Link_AB, @l, @l)) as Link_AB,
if(@sb = Site_B, '', if(@sb := Site_B, @sb, @sb)) as SIte_B,
Link_BC, Site_C
from t cross join
(select @sa := '', @l := '', @sb := '') params
order by t.Site_A, t.Link_AB, t.Site_B;
答案 1 :(得分:0)
您可以在PHP中执行此操作并保持SQL简单和标准:
$query = "SELECT Site_A, Link_AB, Site_B, Link_BC, Site_C
FROM sitelinks
ORDER BY 1, 2, 3, 4, 5";
$result = $mysqli->query($query) or die($mysqli->error());
// maintain an array with previous values
$previous = array();
echo "<table border=1>";
while ($row = $result->fetch_assoc()) {
if (!count($previous)) {
// display column headers
echo "<tr>";
foreach($row as $key => $value) {
echo "<th>" . htmlentities($key) . "</th>";
}
echo "</tr>";
// initialise $previous with empty values for each column:
$previous = array_fill_keys(array_keys($row), '');
}
echo "<tr>";
foreach($row as $key => $value) {
// display value only when different from previous for this column:
echo "<td>".($value !== $previous[$key] ? htmlentities($value) : '')."</td>";
}
// copy current values into $previous
$previous = $row;
echo "</tr>";
}
echo "</table>";
输出: