简体   繁体   中英

Count mutiple column values from table

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM