i have 2 rows in my db: sex (can be only: 1 or 2 "male,female"), foods (various records such: apple, banana, toasts, pasta and so on) i want to associate the most liked food divided by sex. i did something like this but it wont works:
$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
This code will only find the first record which is > 2 but not the most repetitive.
This should help:
$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());
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