简体   繁体   中英

COUNT or SUM of fields in MySql

I have a table in my database which save up to 60 fields with a yes or a no. I am wanting to COUNT or get the SUM off all fields from the table WHERE any of the fields equal to 'yes';

I have tried the following but no luck:

SELECT count(*) FROM information_schema.columns WHERE table_name = 'portraits';

This will return the column count but doesn't allow me to count the fields where they equal to 'yes'.

I am wondering is this easier to do in php? I am currently doing this in codeigniter and I don't know how to read the key/value as it is an object. Any ideas?

SELECT count(*) 
FROM information_schema.columns 
    WHERE table_name = 'portraits'
    AND (field1=0 OR field2=0 OR .... OR fieldN=0);

Try this one.... this simple query gonna work..... :)

SELECT
SUM(IF( information_schema = "YES", 1, 0) AS Yes,
SUM(IF( information_schema != "YES", 1, 0) AS No, 
FROM portraits

Try this :

SELECT state, count(*) FROM information_schema.columns GROUP BY state;

Or in more complicated way :

SELECT y.total, n.total
  FROM (SELECT count(*) as total FROM information_schema.columns WHERE table_name = 'portraits' AND state = 'yes') as y,
       (SELECT count(*) as total FROM information_schema.columns WHERE table_name = 'portraits' AND state = 'no') as n

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