简体   繁体   English

SQL Count具有不同且匹配的两个不同表

[英]SQL Count with distinct and matching two different tables

I have table1 and table2 and I am trying to count the total of unique matches between them for a particular column in each. 我有table1和table2,我试图计算每个中特定列的唯一匹配总数。

select count (distinct phone1) from table1,table2 where table1.phone1=table2.phone2;

I think I am pretty close but I keep getting a syntax error. 我认为我非常接近,但我不断收到语法错误。 I am using distinct to get only the unique matches as there are several duplicate matches. 我使用distinct来获得唯一的匹配,因为有几个重复的匹配。

Thanks! 谢谢!

您的查询看起来正确,您只需要删除count和开括号之间的空格,即应该是count(x)而不是count (x)

Try this: 尝试这个:

SELECT COUNT(phone)
FROM (
    SELECT phone1 AS phone
    FROM table1
    UNION
    SELECT phone2
    FROM table2
) a

UNION will eliminate the duplicate results and then you just COUNT the resulting records. UNION将消除重复的结果,然后您只需计算结果记录。

From the docs : 来自文档

UNION is used to combine the result from multiple SELECT statements into a single result set. UNION用于将多个SELECT语句的结果合并到一个结果集中。

The default behavior for UNION is that duplicate rows are removed from the result. UNION的默认行为是从结果中删除重复的行。

EDIT 编辑

I misunderstood the question. 我误解了这个问题。 I thought you wanted to count all the different numbers. 我以为你想要计算所有不同的数字。

For that, your query was pretty much ok, appart from the space in between COUNT and ( 为此,你的查询非常好,从COUNT和()之间的空间appart

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM