我有一个像这样设置的表:
+----+-------+-------+
| id | col1 | col2 |
+----+-------+-------+
| 1 | John | Mike |
| 2 | Mike | John |
| 3 | Marty | John |
| 4 | Walt | Marty |
| 5 | Walt | Mike |
+----+-------+-------+
我基本上想要计算col1和col2中的唯一值,并将它们与适当的唯一值一起显示.问题是col1不一定包含col2所具有的所有相同名称,反之亦然.我希望得到这样的设置:
+-------+-------+------+
| names | col1 | col1 |
+-------+-------+------+
| John | 1 | 2 |
| Marty | 1 | 1 |
| Mike | 1 | 2 |
| Walt | 2 | NULL |
+-------+-------+------+
我可以使用以下方法独立选择这些值
SELECT col1, count(col1) as count FROM example GROUP BY col1;
要么
SELECT col2, count(col2) as count FROM example GROUP BY col2;
但是我很难理解我如何将这两个计数加在一起,特别是因为这里的值“Walt”没有出现在col2中.
解决方法:
我假设你可能有比你在数据中显示的更多的案例.您可以在col1中使用NULL,您可以将名称仅出现在col1中或仅出现在col2中,等等.
SELECT a.name, c1.`count`, c2.`count`
FROM (SELECT col1 AS name FROM `Table` UNION SELECT col2 FROM `Table`) a
LEFT JOIN (SELECT col1, COUNT(*) AS `count` FROM `Table` GROUP BY col1) c1
ON a.name = c1.col1
LEFT JOIN (SELECT col2, COUNT(*) AS `count` FROM `Table` GROUP BY col2) c2
ON a.name = c2.col2;
说明:
派生表a是出现在任一列中的所有名称的并集.
然后再创建两个派生表,每个表都有一个来自col1的每个名称和它发生的次数,然后是另一个类似于col2中名称的派生故事.
标签:mysql,sql,left-join,outer-join,jointable
来源: https://codeday.me/bug/20190613/1231132.html