0

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

我想搜索useridflag = 0的数学主题的数量。

SQL语句应该怎么写?

我试过了COUNT(subject) AS math FROM books WHERE userid = 'abc' AND flag = '0';

它不起作用。

4

2 回答 2

2

如果您只想获取math带有 的主题userid = 'abc' AND flag = '0',可以使用以下查询:

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

查看SQLFiddle

否则,如果您只想要带有 的主题userid = 'abc' AND flag = '0',那么您query给出的完全可以做到这一点:

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

查看SQLFiddle

为了在php使用中显示,mysql_fetch_assoc您可以提供列名以访问如下值:

$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"];
}
于 2013-09-22T09:11:50.897 回答
0

也许是这样:

SELECT COUNT(subject) AS math
FROM books 
WHERE flag = '0'
GROUP BY userid
HAVING userid = 'abc';
于 2013-09-22T09:10:05.080 回答