如何使用SQL语句来检查一个名为interest_desc的列中的重复条目,然后根据它们分配给它们的categoryID对它们进行排序,只需要一些帮助。
完美的结果将是和回声一样;
“钓鱼”是“4”类别中最受欢迎的兴趣
苦苦于知道从哪里开始:S
更新 - 我现在感谢你的帮助,但我相信我的语法错了吗?
$interestCatPopular = "SELECT interest_desc, categoryID, MAX(num_in_cat) AS num_in_cat FROM
(
SELECT
interest_desc,
categoryID,
COUNT(categoryID) AS num_in_cat
FROM tbl
GROUP BY interest_desc, categoryID
) subsel
GROUP BY interest_desc, categoryID";
$mostPopularInterest = mysql_query($interestCatPopular) or die(mysql_error());
$arrayResults = mysql_fetch_assoc($mostPopularInterest);
foreach ($arrayResults as $result) {
echo "{$result['interest_desc']} was the most popular in category {$result['categoryID']} with {$result['num_in_cat']} occurrences\n";
}
:)
答案 0 :(得分:0)
使用子查询,您可以先计算每个类别中的数字。由此,外部查询选择最大计数以及相应的categoryID
和interest_desc
。
此查询应为每个interest_desc
生成最受欢迎的categoryID
,以及它出现的次数。当然,这是未经测试的。
SELECT interest_desc, categoryID, MAX(num_in_cat) AS num_in_cat FROM
(
SELECT
interest_desc,
categoryID,
COUNT(categoryID) AS num_in_cat
FROM tbl
GROUP BY interest_desc, categoryID
) subsel
GROUP BY interest_desc, categoryID
在PHP中,成功查询并将对mysql_fetch_assoc()
的调用循环到数组$results
之后:
您需要在循环中获取结果:
// Load $arrayResults in a loop...
$arrayResults = array();
while ($row = mysql_fetch_assoc($mostPopularInterest)) {
$arrayResults[] = $row;
}
foreach ($arrayResults as $result) {
echo "{$result['interest_desc']} was the most popular in category {$result['categoryID']} with {$result['num_in_cat']} occurrences\n";
}
答案 1 :(得分:0)
SELECT a.*
FROM
(
SELECT category, interest_desc, COUNT(*) as num
FROM category_table
GROUP BY category,interest_desc
)a
INNER JOIN
(
SELECT category, MAX(num) AS max_num
FROM
(
SELECT category, interest_desc, COUNT(*) as num
FROM category_table
GROUP BY category,interest_desc
)b
GROUP BY b.category
)c ON c.category = a.category AND a.num = c.max_num