2016-08-12 97 views
0

我有一条SQL语句,显示从联系人ID过滤的参与者的所有记录。返回所有记录,并且仅当同一记录中有多个记录时才显示1条记录

<?php 
query = mysql_query("SELECT * FROM participants WHERE contactperson = '$session_id'"); 

while($cys_row = mysql_fetch_array($cys_query)){ 
returns all the records of the participants 
} 
?> 

我发现我的SQL语句添加HAVING从句与同contactperson超过1条记录显示参与者的一种方式。

<?php 
query = mysql_query("SELECT * FROM participants HAVING Count(*)"); 


while($cys_row = mysql_fetch_array($cys_query)){ 
returns all the records of the participants with more than 1 of the same information 
} 
?> 

我需要实现的是,我要选择对contactperson所有的参与者,但只能选择一个记录,如果同一参与者的记录超过1。我怎样才能做到这一点?

回答

0

使用DISTINCT子句中的MySQL:

query = mysqli_query("SELECT DISTINCT(contactperson) AS contactperson, colum2, colum3 FROM participants WHERE contactperson = '$session_id'"); 

在这里,你应该使用mysqli_query(),为的mysql_query已被弃用。

+1

另外,如果有'* session_id'来自客户机的*任何*机会,请使用绑定参数。这应该是显而易见的,但嘿,OP *是*使用mysql_query ... – Will

+0

是的..这就是为什么我建议他使用mysqli_query ...因为mysql_query现在不推荐..并且无论如何mysql_query()将在同样的方式。 @ user866762 –

相关问题