比较两个表中的两列并返回匹配的SUM

时间:2016-05-03 12:35:57

标签: mysql sql database compare

我正在开发一个项目,我必须将两个表一起比较并总结出现次数。对于这个例子,我将使用name作为我想要比较的键。我使用了Union all和Count(*)但是它不会给我所需的输出。

表苹果

+----+-------+---------+
| Id | Name  | Surname |
+----+-------+---------+
|  1 | Adam  | Jaxon   |
|  2 | Adam  | Brixton |
|  3 | Brian | Simpson |
|  4 | Adam  | Steper  |
|  5 | Brian | Bastion |
+----+-------+---------+

表橙

+----+-------+---------+
| id | name  | surname |
+----+-------+---------+
|  1 | Adam  | Thompson|
|  2 | Brian | Coach   |
|  3 | Jhon  | Sinded  |
+----+-------+---------+

Adam有一个名字匹配,Brian有一个匹配,所以我希望得到的输出是

+-------+
| Total |
+-------+
|  3    |
|  1    |
+--------+

我使用的查询与回答问题的人类似,但几乎没有变化。不幸的是,这只返回每个名称的匹配数

SELECT COUNT(*)
FROM
(
SELECT Name
FROM 
apple
UNION ALL
SELECT 
NAME
FROM
orange
) as named
GROUP BY name



+----------+
| Count(*) |
+----------+
|   2    
|   3
+----------+

2 个答案:

答案 0 :(得分:1)

尝试,分组并计算名称:

SELECT 
    id,
    name,
    surname
    count(1) as total
    FROM
    (
        SELECT 
            id,
            name,
            surname
            FROM apple
        UNION ALL
        SELECT 
            id,
            name,
            surname
        FROM orange
    )
GROUP BY name

更新

要在查询之前汇总所有结果:

SELECT sum(total) 
FROM (
        SELECT 
            id,
            name,
            surname
            count(1) as total
            FROM
            (
                SELECT 
                    id,
                    name,
                    surname
                    FROM apple
                UNION ALL
                SELECT 
                    id,
                    name,
                    surname
                FROM orange
            )
    GROUP BY name
)

答案 1 :(得分:0)

没有可用的数据库服务器,所以没有对它进行测试 - 但是应该这样做:

SELECT COUNT(*) FROM
(
    SELECT DISTINCT apple.name FROM apple
        JOIN orange ON apple.name = orange.name
);