0

I am trying to count the entries in rows in a MySQL table:

Example data:

+------------------------------------------------+
| facebook_id | linkedin_id | twitter_id | vk_id |
+------------------------------------------------+
  1234143134    0             13413993     13499
  0             0             0            0
  12313431334   0             13413243     0
  12341431340   13419194319   13419943     13413
  0             0             0            0
+------------------------------------------------+

The aim is to display how many of each _id has an entry. In the above example, facebook has 3, LinkedIn has 1 and twitter has 3 and vk has 2.

Here is my attempt at counting them:

COUNT(`facebook_id`) AS `facebook`,
COUNT(`linkedin_id`) AS `linkedin`,
COUNT(`twitter_id`) AS `twitter`,
COUNT(`vk_id`) AS `vkontakte`
FROM `user`

How can this be fixed? Thanks :)

1 Answer 1

2

Use SUM() like this:

select 
  sum(facebook_id <> 0) facebook, 
  sum(linkedin_id <> 0) linkedin,
  sum(twitter_id <> 0) twitter,
  sum(vk_id <> 0) vk
from `user`

Each of the boolean expressions like:

facebook_id <> 0

evaluates to 1 or 0.
See the demo.
Results:

| facebook | linkedin | twitter | vk  |
| -------- | -------- | ------- | --- |
| 3        | 1        | 3       | 2   |
Sign up to request clarification or add additional context in comments.

2 Comments

we could also write SUM(CASE WHEN facebook_id <> 0 THEN 1 ELSE 0 END) to get an equivalent result +10
Your code is the standard way for this requirement, but since MySql offers this feature I use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.