I have a database that stores peoples interests I have a query that goes through my interests table and lists the most popular interests based on the field categoryID. However all I can display is the categoryID and not the category name, how would I link in my table categories to show the category name and not the id?
This is my query and output:
PHP:
$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 interests
GROUP BY interest_desc, categoryID
) subsel
GROUP BY interest_desc, categoryID";
$mostPopularInterest = mysql_query($interestCatPopular) or die(mysql_error());
$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
";
}
OUTPUT:
football was the most popular in category 9 with 10 occurrences goats was the most popular in category 4 with 1 occurrences Phil was the most popular in category 2 with 59 occurrences
Thanks
table structure -
interests:
Field Type Collation Attributes Null Default Extra Action
interestID int(11) No None AUTO_INCREMENT
name varchar(100) utf8_general_ci No None
categoryID varchar(30) utf8_general_ci No None
interest_desc text utf8_general_ci No None
date timestamp No CURRENT_TIMESTAMP
categories:
Field Type Collation Attributes Null Default Extra Action
categoryID int(11) No None AUTO_INCREMENT
category_desc varchar(100) utf8_general_ci No None
Why didn't you just join the two tables like this:
SELECT interest_desc,
(
select categoryName
from categories where categoryID = subsel.categoryId
), MAX(num_in_cat) AS num_in_cat
FROM (
SELECT interest_desc, categoryID,
COUNT(categoryID) AS num_in_cat
FROM interests GROUP BY interest_desc, categoryID
)
subsel
GROUP BY interest_desc, categoryID