Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...