Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

count - MySQL - Counting two things with different conditions

I want to count two things under different conditions in one query.

SELECT COUNT(*) AS count FROM table_name WHERE name = ?

and

SELECT COUNT(*) as count FROM table_name WHERE address = ? AND port = ?

I need to have a count for rows that have a certain address and certain port, and a SEPARATE count for rows that have a certain name.

I'm aware that I could do

SELECT (COUNT*) as count FROM table_name WHERE (address = ? AND port = ?) OR name = ?

However that is a single count, and I need them to be separate so I can display a more accurate message to the user.

How might I go about doing this? Help would be appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What about simply:

SELECT 
    SUM(IF(name = ?, 1, 0)) AS name_count,
    SUM(IF(address = ? AND port = ?, 1, 0)) AS addr_count
FROM 
    table_name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...