首先让我展示我的表格数据,然后我将解释我的问题。
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