简体   繁体   中英

How to count distinct values in SQL union?

I can select distinct values from two different columns, but do not know how to count them. My guess is that i should use alias but cant figure out how to write statement correctly.

$sql =  "SELECT DISTINCT author FROM comics WHERE author NOT IN 
                ( SELECT email FROM bans ) UNION
                SELECT DISTINCT email FROM users WHERE email NOT IN 
                ( SELECT email FROM bans ) ";

Edit1: i know that i can use mysql_num_rows() in php, but i think that takes too much processing.

You could wrap the query in a subquery:

select  count(distinct author)
from    (
        SELECT  author
        FROM    comics 
        WHERE   author NOT IN ( SELECT email FROM bans ) 
        UNION ALL
        SELECT  email 
        FROM    users 
        WHERE   email NOT IN ( SELECT email FROM bans )
        ) as SubQueryAlias

There were two distinct s in your query, and union filters out duplicates. I removed all three (the non-distinct union is union all ) and moved the distinctness to the outer query with count(distinct author) .

您总是可以执行SELECT COUNT(*) FROM (SELECT DISTINCT...) x ,只需将UNION复制到第二个SELECT (更确切地说,它称为匿名视图)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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