如何计算SQL联合中的不同值?
我可以从两个不同的列中选择不同的值,但不知道如何计算它们。 我的猜测是我应该使用别名,但无法弄清楚如何正确编写语句。
$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:我知道我可以在 php 中使用 mysql_num_rows() ,但我认为这需要太多处理。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将查询包装在子查询中:
查询中有两个不同的查询,并且联合会过滤掉重复项。我删除了所有三个(非独特联合是
union all
),并使用count(distinctauthor)
将独特性移至外部查询。You could wrap the query in a subquery:
There were two
distinct
s in your query, andunion
filters out duplicates. I removed all three (the non-distinct union isunion all
) and moved the distinctness to the outer query withcount(distinct author)
.您始终可以执行
SELECT COUNT(*) FROM (SELECT DISTINCT...) x
并将该UNION
复制到第二个SELECT
(更多准确地说,它称为匿名视图)。You can always do
SELECT COUNT(*) FROM (SELECT DISTINCT...) x
and just copy thatUNION
into the secondSELECT
(more precisely, it's called an anonymous view).