简体   繁体   English

如何在一个查询中进行多个计数/存在?

[英]How to do multiple counts / exists in one query?

I'm struggling to figure out how I can check for two things from one table without making two calls to mysql. 我正在努力弄清楚如何可以在不对mysql进行两次调用的情况下从一张表中检查两件事。

I have a Members table. 我有一个Members表。 I'd like to test whether a certain value exists in the MemberID column, and whether a certain value exists in the PhoneNumber column. 我想测试MemberID列中是否存在某个值,以及PhoneNumber列中是否存在某个值。 MemberID and PhoneNumber are both indexed. MemberIDPhoneNumber都已建立索引。

But there's something wrong with the syntax I'm trying. 但是我尝试的语法有问题。 For example, each of 例如,每个

SELECT COUNT(1) AS IDExists FROM Members WHERE MemberID = '999999999999' LIMIT 1

and

SELECT COUNT(1) AS PhoneExists FROM Members WHERE PhoneNumber = '5555555555' LIMIT 1

works. 作品。 Why can't they be combined, somehow, like 为什么不能将它们合并在一起,就像

SELECT (COUNT(1) AS IDExists FROM Members WHERE MemberID = '999999999999' LIMIT 1), (COUNT(1) AS PhoneExists FROM Members WHERE PhoneNumber = '5555555555' LIMIT 1)

?

Or perhaps, since I only care whether the value occurs zero times, or at all, something like 也许是因为我只关心该值是否出现零次,或者根本不出现,所以

SELECT EXISTS (SELECT 1 FROM Members WHERE MemberID = '999999999999')

?

But, unfortunately, there's something wrong with that syntax even for the case of one of my inquiries. 但是,不幸的是,即使对于我的查询之一,该语法还是有问题的。

Any suggestions on how to accomplish this? 关于如何做到这一点的任何建议?

You want a conditional SUM 您需要有条件的SUM

SQL FIDDLE SQL字段

SELECT 
    SUM( CASE 
             WHEN PhoneNumber = '5555555555' THEN 1
             ELSE 0
         END) PhoneExists,
    SUM( CASE 
             WHEN MemberID = '999999999999' THEN 1
             ELSE 0
         END) IDExists
FROM Members

You can combine two working query like this: 您可以像这样结合两个有效的查询:

select a.IDExists, b.PhoneExists
from (SELECT COUNT(1) AS IDExists FROM Members WHERE MemberID = '999999999999' LIMIT 1) a,
     (SELECT COUNT(1) AS PhoneExists FROM Members WHERE PhoneNumber = '5555555555' LIMIT 1) b

Though the query join two results with cartesian product, it is guaranteed that each result has only one row, it would not be a problem. 尽管查询将两个结果与笛卡尔积连接在一起,但是可以确保每个结果只有一行,这不会有问题。

I'm not sure how big is the table and what kinds of index it has. 我不确定表有多大以及它具有什么样的索引。 If the table is big, then perhaps you have indexes on column MemberID and PhoneNumber respectively, then the above query will return the result quickly. 如果表很大,那么也许您分别在MemberIDPhoneNumber列上都有索引,那么上面的查询将快速返回结果。

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

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