2012-08-10 42 views
0

我對PHP MYSQL 這個問題,這是我的數據庫樣本PHP的MySQL檢查行,有多少相同的電子郵件

id word email 
1 Helo [email protected] 
2 Sim [email protected] 
3 Sam [email protected] 
4 Mac [email protected] 
5 Mimic [email protected] 

現在我試圖在這裏解決的是,我怎麼能算的與例如 OUTPUT網頁相同的電子郵件發送電子郵件至:

id word email   submitted words dictionary 
1 Helo [email protected]  3   regular 
2 Sim [email protected]  3   regular 
3 Sam [email protected]  3   regular 
4 Mac [email protected]  2   regular 
5 Mimic [email protected]  2   regular 

提交的話是電子郵件的數量。 我如何可以解決這個問題上的PHP計數相同的電子郵件和輸出3 ...

回答

1

使用此查詢:

SELECT email, COUNT(*) AS nb_emails 
FROM your_table 
GROUP BY `email` 

它將返回爲表格中的每封電子郵件分配關聯記錄的數量。

如果您正在使用mysql_* functions,您可以使用代碼獲取所有值:

$sql = "SELECT email, COUNT(*) AS nb_emails 
      FROM your_table 
      GROUP BY `email`"; 
$res = mysql_query($sql); 
while($row = mysql_fetch_assoc($res)) 
{ 
    // do something with the values of the last fetched record. The values are stored in $row['email'] and $row['nb_emails'] 
} 

注意:使用的MySQL擴展氣餒。相反,應該使用MySQLiPDO_MySQL擴展名。有關更多信息,另請參閱MySQL: choosing an API指南和related FAQ

+0

我怎麼能取嗎? '$ row = mysql_fetch_array($ sql)'是正確的,然後$ row ['nb_emails']; – Butternut 2012-08-10 10:27:37

+0

@ user1538668我剛剛更新了我的答案。 – Jocelyn 2012-08-10 13:16:23

0

使用mysql_num_rows()例如:

//mysql_connect() & mysql_select_db()  
$q=mysql_query("SELECT * FROM tablename WHERE email='[email protected]'"); 
$count=mysql_num_rows($q); //3 
0

試試這個:

SELECT a.ID, a.Word, a.Email, b.SubmittedWords 
FROM myTable a INNER JOIN 
     (
      SELECT email, COUNT(*) SubmittedWords 
      FROM mytable 
      GROUP BY email 
     ) b 
      ON a.email = b.email 
0

使用此:

select email, 
count(email) as count_same 
from table_users 
group by email 
having (count(email) > 1); 
相關問題