简体   繁体   中英

Count the number of rows in database where multiple field is equal to different value

Table books :

subject  |  userid  |  flag
---------+----------+--------
math     |  abc     |  0
math     |  abc     |  0
english  |  xyz     |  0

I wanna search the number of math subject where userid and flag = 0 .

How should I write the SQL statement?

I tried COUNT(subject) AS math FROM books WHERE userid = 'abc' AND flag = '0';

It doesn't work.

If you want to get only the math subjects with userid = 'abc' AND flag = '0' , you can use below query:

SELECT COUNT(subject) AS math 
FROM books WHERE userid = 'abc' AND flag = '0' AND subject = 'math';

check out the SQLFiddle

otherwise if you only want subjects with userid = 'abc' AND flag = '0' , the query given by you is perfectly doing that:

SELECT COUNT(subject) AS math 
FROM books WHERE userid = 'abc' AND flag = '0';

check out the SQLFiddle

For displaying in php using mysql_fetch_assoc you can give the column name to access the value like this:

$sql = "SELECT COUNT(subject) AS math 
    FROM books WHERE userid = 'abc' AND flag = '0'";

$result = mysql_query($sql);

if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No math subjects exist";
    exit;
}
while ($row = mysql_fetch_assoc($result)) {
    echo $row["math"];
}

Maybe this:

SELECT COUNT(subject) AS math
FROM books 
WHERE flag = '0'
GROUP BY userid
HAVING userid = 'abc';

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