MYSQL查询,加入2表的问题

时间:2012-05-03 06:23:56

标签: mysql join group-by

我有这个查询 -

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

我想更改它,以便最终可以从名为categories的单独表中显示类别名称。我可以显示的是来自categoryID的{​​{1}}和这个sql

两个表结构都是

interests

类别表结构

#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   

我知道需要某种类型的连接但是我已经查看了示例并且正在努力获得确切的语法。

我在php脚本中有这个 - echo语句就是这个

# 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

并且它的输出是这个 -

"{$result['interest_desc']} was the most popular in category   {$result['categoryID']}    with {$result['num_in_cat']} occurrences\n";

我希望输出为“阿迪达斯是体育界最受欢迎的一次出场”

但是我的sql查询没有"Adidas was the most popular in category 5 with 1 occurrences"

4 个答案:

答案 0 :(得分:2)

这是更快速的表现

SELECT subsel.interest_desc, subsel.categoryID, cat.category_desc, 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 
     inner join categories as cat on subsel.categoryID = cat.categoryID
     GROUP BY interest_desc, subsel.categoryID

答案 1 :(得分:1)

请检查一下,它会给你所需的结果。

SELECT subsel.interest_desc, cat.category_desc, 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 
 inner join categories as cat on subsel.categoryID = cat.categoryID
 GROUP BY interest_desc, subsel.categoryID

答案 2 :(得分:0)

SELECT * FROM interests i LEFT JOIN categories c ON i.categoryID = c.categoryID

我还没有测试过。可能存在语法错误。

答案 3 :(得分:0)

我不知道在哪些现实场景中你发布的两个类似的查询是有意义的。我会说你可以直接使用这个:

SELECT     i.interest_desc, c.category_desc, COUNT(i.categoryID) AS num_in_cat
FROM       interests AS i
INNER JOIN categories AS c USING (categoryID)
GROUP BY   i.interest_desc, i.categoryID