1

我的数据库中有 2 行:性别(只能是:1 或 2 个“男性、女性”)、食物(各种记录,例如:苹果、香蕉、吐司、意大利面等)我想关联最喜欢的食物划分按性别。我做了这样的事情,但它不会工作:

$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 但不是最重复的第一条记录。

4

2 回答 2

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
于 2012-04-24T14:55:23.883 回答
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());
于 2012-04-24T14:24:47.347 回答