如果唯一的姓名,如何打印姓氏?否则将全名打印为“姓氏,名字”。
示例:在数据库中,您有:Ace Perez,Dan Perez,James Perez和Dan Bond。它应该显示如下内容:
Perez Ace Perez Dan Perez James Bond它只显示Bond而不是Bond Dan,因为它是一个独特的姓氏。
这是我的代码段:
<?php
$display = "SELECT * FROM main ORDER BY lastName ASC, firstName ASC";
$result = @mysql_query($display)or die(mysql_error());
while($row = mysql_fetch_array($result)){
$lastName = $row['lastName'];
$firstName = $row['firstName'];
$score = $row['score'];
$totalScore = $row['totalScore'];
$percentage = ($score/$totalScore)*100;
echo "<tr>";
echo "<td align='left'> $lastName </td>";
echo "<td align='left'> $firstName </td>";
echo "<td align='left'> $percentage </td>";
echo "</tr>";
}
echo "</table>";
?>
编辑:抱歉,我在这里很新。该片段现在应该正常显示! :)
答案 0 :(得分:1)
您可以通过计算姓氏上的匹配数来完成此操作。然后将其用于条件select
:
select m.lastname, (case when cnt > 1 then m.firstname end) as firstname
from main m join
(select lastname, count(*) as cnt
from main
group by lastname
) ml
on m.lastname = ml.lastname;
答案 1 :(得分:0)
如果您有主键,则可以使用CASE
和EXISTS
的简单查询;
SELECT
lastname,
CASE WHEN EXISTS
( SELECT 1 FROM test t2 WHERE t1.lastname=t2.lastname AND t1.id<>t2.id )
THEN firstname ELSE '' END firstname
FROM test t1