Question

Is it possible to do this:

SELECT COUNT(username) as username FROM users WHERE username = 'Piet';
SELECT COUNT(email) as email FROM users WHERE email = 'piet@google.nl';
SELECT COUNT(ip_registed) as ip FROM users WHERE ip = '127.0.0.1';

In one query (so without subqueries)?

Was it helpful?

Solution

Yes you can use SUM() this should do the trick, using sum with expression will result in a boolean 1 or 0,so when your expression evaluates to true this will give you the count accordingly,also when aggregate functions are used without group they will result in a single row,and assume the whole table as one group

SELECT
SUM(username = 'Piet') as username,
SUM(email = 'piet@google.nl') as email,
SUM(ip = '127.0.0.1') as ip
FROM users
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top