2014-02-16 72 views
0

如何僅在姓名唯一時才顯示姓氏?否則打印全名作爲'姓氏,名字'。例如:在數據庫中,您有:Ace Perez,Dan Perez,James Perez和Dan Bond。它應該顯示是這樣的:僅當姓氏不唯一時才顯示名字

佩雷斯王牌佩雷斯丹·佩雷斯詹姆斯·邦德

它只能顯示債券而不是債券丹,因爲它是一個獨特的姓氏。

這裏是我的代碼片段:

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

如果你有一個主鍵,你可以使用一個簡單的查詢與CASEEXISTS;

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

+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; 
+0

[SQL小提琴](http://sqlfiddle.com/#!2/974d814/5) –