2016-08-12 122 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 –

相關問題