我有这个mysql代码,可以根据它们在数据库中出现的次数来检索每个类别中最受欢迎的描述 -
它抓住了列表,但它回显了像这样的数据
"Adidas was the most popular in category 5 with 1 occurrences"
我对这种兴趣(兴趣爱好)的表结构是
# interests
CREATE TABLE `interests` (
`interestID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`categoryID` int(11) NOT NULL,
`sessionID` int(11) NOT NULL,
`interest_desc` varchar(30) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`interestID`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
# categories
CREATE TABLE `categories` (
`categoryID` int(11) NOT NULL AUTO_INCREMENT,
`category_desc` varchar(100) NOT NULL,
PRIMARY KEY (`categoryID`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
这是我的SQL命令:
SELECT
interest_desc,
categoryID,
MAX(num_in_cat) AS num_in_cat,
category_name
FROM
(
SELECT interest_desc, categoryID, COUNT(categoryID) AS num_in_cat
FROM interests
GROUP BY interest_desc, categoryID
) subsel
JOIN categories ON subsel.categoryID = categories.ID
GROUP BY interest_desc, categoryID, category_name
我收到此错误:
不唯一的表/别名:'categories'
答案 0 :(得分:1)
完成此操作需要完成针对categories
表的内部联接(提供正确的表名和列名):
SELECT
interest_desc,
categoryID,
MAX(num_in_cat) AS num_in_cat,
category_name
FROM
(
SELECT interest_desc, categoryID, COUNT(categoryID) AS num_in_cat
FROM interests
GROUP BY interest_desc, categoryID
) subsel
JOIN categories ON subsel.categoryID = categories.ID
GROUP BY interest_desc, categoryID, category_name
答案 1 :(得分:0)
试试这些:
如果有效,可以更加优化,加入
SELECT s.interest_desc, c.name, MAX(s.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
) s
INNER JOIN categories c ON c.ID = s.categoryID
GROUP BY s.interest_desc, s.categoryID
或者
将另一个选择添加为列
不太理想 SELECT s.interest_desc, (SELECT name from categories c WHERE c.ID = s.categoryID), MAX(s.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
) s
GROUP BY s.interest_desc, s.categoryID