[英]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 . 我想搜索userid和flag = 0的数学主题的数量。
How should I write the SQL statement? 我该如何编写SQL语句?
I tried COUNT(subject) AS math FROM books WHERE userid = 'abc' AND flag = '0';
我试过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: 如果您只想使用userid = 'abc' AND flag = '0'
获得math
科目,您可以使用以下查询:
SELECT COUNT(subject) AS math
FROM books WHERE userid = 'abc' AND flag = '0' AND subject = 'math';
check out the SQLFiddle 看看SQLFiddle
otherwise if you only want subjects with userid = 'abc' AND flag = '0'
, the query
given by you is perfectly doing that: 否则,如果你只想要使用userid = 'abc' AND flag = '0'
,那么你给出的query
就是这样做的:
SELECT COUNT(subject) AS math
FROM books WHERE userid = 'abc' AND flag = '0';
check out the SQLFiddle 看看SQLFiddle
For displaying in php
using mysql_fetch_assoc
you can give the column name to access the value like this: 要使用mysql_fetch_assoc
在php
显示,您可以使用列名来访问值,如下所示:
$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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.