0

It's a simple table that looks like this:

id TEXT,
name TEXT,
FOREIGN KEY(id) REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY(id, name)

What I want is to be able to get a set of rows with counts for all names in that table. Basically how many times each name is present in the table.

This is my code so far and it works:

var names = ['upload_files', 'create_users', 'remove_users', 'edit_tags'];

var query = 'SELECT COUNT(p.id) AS count FROM perms p JOIN users u ON p.id = u.id WHERE p.name = ?',

for(let name of names){
  this.db.prepare(query).all([name]).map(value => data[name] = value.count);
}

It produces something like this:

upload_files: 5,
create_users: 2,
remove_users: 2,
edit_tags: 5,

Assuming there are 5 rows with upload_files, 2 rows with remove_users and so on...

But it's very slow when I have 50K records, each query takes 2 seconds.

Can it be combined in a single query? that way I can reduce the time to 2 seconds for all names

1 Answer 1

1

Filter the names using IN and group by the name.

SELECT p.name,
       count(p.id) count
       FROM perms p
       WHERE p.name IN ('upload_files',
                        'create_users',
                        'remove_users',
                        'edit_tags')
       GROUP BY p.name;

And consider to try if an index on name speeds things up.

1
  • thanks it works :D but I could swear I tried group by before and it gave me a single row with all counts!
    – Alex
    Jan 12, 2019 at 20:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.