MySQL GROUP & COUNT Multiple tables

风流意气都作罢 提交于 2019-12-02 05:58:53

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

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