计算MYSQL中的非空字段

时间:2014-09-19 12:48:14

标签: mysql sql

我有这个简单的MYSQL table1:

id
 1
 2
 3

和这个表2:

 id | question | answer
  1 |  how     | 
  2 |  are     | fine
  3 |  you     | ok

这个简单的查询:

SELECT table1.id,COUNT(answer NOT NULL) FROM table1 LEFT JOIN table2
       ON table1.id = table2.id

我想计算非空答案字段。我尝试了NOT NULL,但由于answer列为NOT NULL而无效,因此它不适用,因为它会导致主查询不返回任何内容

7 个答案:

答案 0 :(得分:2)

您可以使用CHAR_LENGTH(str)函数来检查值的长度。 使用以下查询:

SELECT COUNT(answer) FROM table WHERE CHAR_LENGTH(answer)>0;   

来自Reference Doc.

编辑:
您可以尝试此查询:

SELECT COUNT(answer) FROM table1 LEFT JOIN table2
       ON table1.id = table2.id AND CHAR_LENGTH(table2.answer)>0

答案 1 :(得分:1)

你可以试试这个,捕捉空白的一切:

SELECT COUNT(id) FROM table
where answer IS NOT NULL or answer <>''

这应该抓住并计算“回答”中具有任何值的任何行。

或者,如果有联接:

SELECT     table1.count(id), table2.question
FROM         table1 LEFT OUTER JOIN
                      tabel1 ON table1.id = table2.id
GROUP BY table1.id,table2.question
HAVING      (table2.answer <> '') OR (table2.answer IS NOT NULL)

答案 2 :(得分:0)

只计算具有NULL答案的行数!

SELECT COUNT(1) FROM table /* COUNT(1) will go on counting rows frequncy*/
where answer IS NOT NULL

答案 3 :(得分:0)

如果答案列不可为空,则IS NOT NULL将返回所有行。你想要的是“不是空字符串”:

SELECT COUNT(*)
FROM table
WHERE answer <> "";

如果答案可以为空,那么您可以检查两种情况:

SELECT COUNT(*)
FROM table
WHERE answer IS NOT NULL AND answer <> "";

答案 4 :(得分:0)

   SELECT COUNT(t2.answer) count
     FROM table1 t1 
LEFT JOIN table2 t2
       ON t2.id = t1.id
      AND t2.answer != ''

OR

   SELECT t1.id, COUNT(t2.answer) count
     FROM table1 t1 
LEFT JOIN table2 t2
       ON t2.id = t1.id
      AND t2.answer != ''
 GROUP BY t1.id

答案 5 :(得分:0)

您可以使用此SUM(CHAR_LENGTH((answer))/CHAR_LENGTH((answer)))公式计算非空答案字段。

SELECT table1.id, SUM(CHAR_LENGTH((answer))/CHAR_LENGTH((answer))) FROM table1 

LEFT JOIN table2 ON table1.id = table2.id

答案 6 :(得分:0)

计算每个列:

SELECT count(`id`) + count(`personal_id`) + count(`f_name`) + ... 
FROM `detail_members` WHERE `personal_id` = '$personalid'