MySQL GROUP & COUNT Multiple tables

蹲街弑〆低调 提交于 2019-12-20 03:52:23

问题


I have a 3 part problem thats been giving me trouble I know how to get the tables to work if I query 1 table at a time but I can't seem to figure out how I can combine both the tags and more_tags tables to get the same results.

The 3 main problems I have are Listed below.

PROBLEM 1

I want to be able to group the same tag from both the tags and more_tags tables.

PROBLEM 2

I also want to be able to display the tags from each table that are not present in the other table.

PROBLEM 3

I also want to count the total amount of times the tag appears in both tags and more_tags tables.

MYSQL Tables

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
GROUP BY `tags`.`tag_name` 
ORDER BY `tags`.`tag_name` ASC";


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
GROUP BY `more_tags`.`tag_name` 
ORDER BY `more_tags`.`tag_name` ASC";             

Desired output

tag_id  tag_name    num
10  apple   12
192     pear    1
197     bored   1
203     sad     3
207     ads     2
217     news    1
190     bf  1
196     cape    1

回答1:


Problem 1:

SELECT tag_id, tag_name, count(*)
FROM (
  SELECT tag_id, tag_name FROM tags
  UNION ALL
  SELECT tag_id, tag_name FROM more_tags
) s
GROUP BY tag_id, tag_name

Problem 2:

SELECT tag_id, tag_name, 'not present in more tags' as description
FROM tags LEFT JOIN more_tags ON tags.tag_id=more_tags.tag_id
WHERE more_tags.tag_id IS NULL
UNION ALL
SELECT tag_id, tag_name, 'not present in tags' as description
FROM tags RIGHT JOIN more_tags ON tags.tag_id=more_tags.tag_id
WHERE tags.tag_id IS NULL

Problem 3:

SELECT tag_id, tag_name, COUNT(*)
FROM tags INNER JOIN more_tags ON tags.tag_id=more_tags.tag_id
GROUP BY tag_id, tag_name



回答2:


You can use UNION to add together the results sets from two queries iff those queries return rows with the same structure (that is, if the first column in the first query is an int, then the first column in the second query must be an int, and so on). Read all about it in http://dev.mysql.com/doc/refman/5.1/en/union.html

Once you've written the two selects and joined them with a UNION statement, you can use that as a subquery for GROUP BY or other things:

SELECT * FROM (
(SELECT 1 AS ticked, col1, col2 FROM table1 INNER JOIN table2 USING (col3))
    UNION
(SELECT 0 AS ticked, col1, col2 FROM table1)
) AS combined_table /*derived tables need a unique name*/
GROUP BY col1 /*group by the unique col1 to stop duplicates*/
ORDER BY ticked DESC


来源:https://stackoverflow.com/questions/14736315/mysql-group-count-multiple-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!