MySQL UNION COUNT

时间:2013-02-07 04:49:49

标签: mysql count group-by union

首先让我展示我的表数据,然后我将解释我的问题。

MySQL表格结构

CREATE TABLE more_tags (
tag_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
more_id INT UNSIGNED NOT NULL,
user_id INT UNSIGNED NOT NULL,
tag_name VARCHAR(255) NOT NULL,
PRIMARY KEY (tag_id),
UNIQUE KEY (more_id, user_id, tag_name)
);

CREATE TABLE tags(
tag_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
another_id INT UNSIGNED NOT NULL,
user_id INT UNSIGNED NOT NULL,
tag_name VARCHAR(255) NOT NULL,
PRIMARY KEY (tag_id),
UNIQUE KEY (another_id, user_id, tag_name)
);

more_tads表数据

tag_id  tag_name
10      apple 
192     apple 
197     apple 
203     apple 
207     apple 
217     news 
190     bff
196     cape

标记表格数据

tag_id  tag_name
1       apple 
2       time 
3       bff

好的我早些时候问过一些类似的问题。但是现在由于某种原因,我无法通过查询来计算两个表中的标记,它只计算来自一个表的标记,如下例所示

当前输出

tag_id  tag_name    num
1       apple       5
2       bff         1
3       cape        1
4       time        1

但是我想对所有类似的标签进行分组并计算它们在表格中找到的次数,如下例所示

所需输出

tag_id  tag_name    num
1       apple       6
2       bff         2
3       cape        1
4       time        1

当前的MySQL QUERY

SELECT *
FROM(SELECT `more_tags`.`tag_id`, `more_tags`.`tag_name`, COUNT(`more_tags`.`tag_name`) as 'num' 
FROM `more_tags` 
INNER JOIN `users` ON `more_tags`.`user_id` = `users`.`user_id` 
WHERE `users`.`active` IS NULL 
AND `users`.`deletion` = '0' 
GROUP BY `more_tags`.`tag_name`
UNION(
SELECT `tags`.`tag_id`, `tags`.`tag_name`, COUNT(`tags`.`tag_name`) as 'num' 
FROM `tags` 
INNER JOIN `users` ON `tags`.`user_id` = `users`.`user_id` 
WHERE `users`.`active` IS NULL 
AND `users`.`deletion` = '0' 
GROUP BY `tags`.`tag_name`))
AS table_1 
GROUP BY `tag_name`  
ORDER BY `tag_name` ASC

2 个答案:

答案 0 :(得分:0)

你想要的输出中的tag_id对我来说真的没有意义。如果没有,那么你如何得到你所要求的:

SELECT tag_name, SUM(num)
FROM(SELECT `more_tags`.`tag_name`, COUNT(*) as 'num' 
FROM `more_tags` 
INNER JOIN `users` ON `more_tags`.`user_id` = `users`.`user_id` 
WHERE `users`.`active` IS NULL 
AND `users`.`deletion` = '0' 
GROUP BY `more_tags`.`tag_name`
UNION ALL
SELECT `tags`.`tag_name`, COUNT(*) as 'num' 
FROM `tags` 
INNER JOIN `users` ON `tags`.`user_id` = `users`.`user_id` 
WHERE `users`.`active` IS NULL 
AND `users`.`deletion` = '0' 
GROUP BY `tags`.`tag_name`)
AS table_1 
GROUP BY `tag_name`  
ORDER BY `tag_name` ASC

SQL移除用户逻辑以演示关键点:http://sqlfiddle.com/#!2/ea44d/2

另外,请不要忘记UNION ALL SUM ,它们是您问题中缺少的关键部分。如果没有UNION ALL,你可能会将一些行作为重复行拒绝,因为它们不像我在小提琴中给出的那样。

答案 1 :(得分:0)

这将输出您想要的结果。只需在Sub查询中添加用户联接。

SELECT a.tag_id, a.tag_name, SUM(a.num)
FROM (
     SELECT tag_id, tag_name, SUM(1) as num  FROM tags
        GROUP BY tag_name
     UNION
     SELECT tag_id, tag_name, SUM(1) as num  FROM more_tags
        GROUP BY tag_name
      ) a
GROUP BY a.tag_name