douluan5738 2014-02-16 15:49
浏览 101
已采纳

仅当姓氏不唯一时才显示名字

How to print the last name only, whenever it is unique? Else print the full name as 'last name, first name'.

Example: In the database, you have: Ace Perez, Dan Perez, James Perez and Dan Bond. It should display something like:

Perez Ace Perez Dan Perez James Bond

It will only display Bond instead of Bond Dan, since it's a unique last name.

Here is my code snippet:

<?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>";
?>

Edit: Sorry, I'm quite new here. The snippet should be displaying properly now! :)

  • 写回答

2条回答 默认 最新

  • dongshi1869 2014-02-16 16:03
    关注

    If you have a primary key, you could use a simple query with CASE and 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
    

    An SQLfiddle to test with.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测