1

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

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 查询

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
4

2 回答 2

0

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

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
于 2013-02-07T05:23:06.273 回答
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 Fiddle 演示关键点:http ://sqlfiddle.com/#!2/ea44d/2

另外不要忘记 UNION ALLSUM是您问题中缺少的关键部分。如果没有 UNION ALL,当某些行不在我在小提琴中给出的示例中时,它们可能会被拒绝为重复行。

于 2013-02-07T05:14:56.077 回答