2012-04-24 112 views
1

我在我的db中有兩行:性別(可以是:1或2「男性,女性」),食物(各種記錄如蘋果,香蕉,烤麪包,意大利麪等) 我想把最喜歡的食物分爲性別。 我做了這樣的事情,但它不會工作:根據兩個字段查找大多數重複條目的Mysql查詢

$most_male = mysql_query("SELECT * FROM data WHERE sex = '1' GROUP BY foods HAVING count(*) > 2") or die(mysql_error()); //do something 

$most_female= mysql_query("SELECT * FROM data WHERE sex = '2' GROUP BY foods HAVING count(*) > 2") or die(mysql_error()); //do something 

這個代碼將只發現這是> 2,但不是最重複的第一個記錄。

回答

0

這應有助於:

$most_male = mysql_query("SELECT count(*) as Count,`foods` FROM `data` WHERE `sex` = '1' GROUP BY `foods` ORDER BY `Count` DESC") or die(mysql_error()); 

$most_female = mysql_query("SELECT count(*) as Count,`foods` FROM `data` WHERE `sex` = '0' GROUP BY `foods` ORDER BY `Count` DESC") or die(mysql_error()); 
+0

非常感謝你。 – user1084304 2012-04-30 20:51:47

0
SELECT * 
FROM (SELECT sex, foods, COUNT(*) 
     FROM data 
     WHERE sex=1 
     GROUP BY sex, food 
     HAVING COUNT(*)>2 
     ORDER BY COUNT(*) DESC 
     LIMIT 0,1 
) ilv1 
UNION 
SELECT * 
FROM (SELECT sex, foods, COUNT(*) 
     FROM data 
     WHERE sex=2 
     GROUP BY sex, food 
     HAVING COUNT(*)>2 
     ORDER BY COUNT(*) DESC 
     LIMIT 0,1 
) ilv2