[英]Displaying the first name, only if the last name is not unique
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. 示例:在数据库中,您有:Ace Perez,Dan Perez,James Perez和Dan Bond。 It should display something like:
它应该显示如下内容:
Perez Ace Perez Dan Perez James Bond 佩雷斯Ace佩雷斯Dan Perez James Bond
It will only display Bond instead of Bond Dan, since it's a unique last name. 因为这是唯一的姓氏,所以只会显示Bond而不是Bond Dan。
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!
该代码段现在应该正确显示! :)
:)
You can do this by counting the number of matches on the last name. 您可以通过计算姓氏上的匹配数来完成此操作。 Then use this for a conditional
select
: 然后将其用于条件
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;
If you have a primary key, you could use a simple query with CASE
and EXISTS
; 如果您有主键,则可以对
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.