计算重复条目并根据类别对它们进行排序
只需要一些帮助来了解如何使用 SQL 语句来检查名为interest_desc 的列中的重复条目,然后根据它们分配到的类别 ID 对它们进行排序。
完美的结果将是和 echo 一样;
“钓鱼”是类别“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";
}
:)
Just need some help on how to go about using a SQL statement that checks for duplicate entries in a column called interest_desc and then sorts them by what categoryID they are assigned to.
The perfect outcome would be and echo like;
"Fishing" is the most popular interest in the category "4"
Struggling to know where to begin :S
Update - I have this now thanks to your help however i believe my syntax is wrong?
$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";
}
:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用子查询,您可以首先统计每个类别的数量。由此,外部查询选择最大计数以及相应的
categoryID
和interest_desc
。此查询应该为每个
categoryID
生成最流行的interest_desc
,以及它出现的次数。当然,这是未经测试的。在 PHP 中,成功查询并将
mysql_fetch_assoc()
循环调用到数组$results
中:更新
您需要在循环中获取结果:
Using a subquery, you can first count the number in each category. From that, the outer query selects the maximum count along with the corresponding
categoryID
andinterest_desc
.This query should result in the most popular
interest_desc
for eachcategoryID
, plus how many occurrences it had. Of course, it's untested.In PHP, following a successful query and looping call to
mysql_fetch_assoc()
into an array$results
:Update
You need to fetch your results in a loop: