PHP / MySQL - 计算具有给定前缀的字段数

时间:2012-06-15 06:07:15

标签: php mysql

是否可以计算具有给定前缀的填充字段数?

e.g。我有一个Q&表和多选答案。有时一个问题有3个答案选项,有时会有4个或5个答案。每个答案都在answer1_aanswer1_banswer1_c等字段中,是否有办法确定这些字段中有多少具有数据(对于给定的记录)?我需要这个来确定HTML中提供多少选项。

也许以某种方式使用 mysql_num_fields

感谢, 杰夫

2 个答案:

答案 0 :(得分:2)

鉴于你的桌面结构,Kaii的答案是正确的。

对于未来,我建议使用这样的真实关系模型:

CREATE TABLE QUESTION(
  ID INTEGER NOT NULL,
  QUESTION VARCHAR(100) NOT NULL,

  PRIMARY KEY (ID)
);

INSERT INTO QUESTION VALUES(1, 'My first question');
INSERT INTO QUESTION VALUES(2, 'My second question');
INSERT INTO QUESTION VALUES(3, 'My third question');

CREATE TABLE ANSWER(
  ID INTEGER NOT NULL,
  ID_QUESTION INTEGER NOT NULL,
  ANSWER VARCHAR(100) NOT NULL,

  PRIMARY KEY (ID),
  FOREIGN KEY (ID_QUESTION) REFERENCES QUESTION(ID)
);

INSERT INTO ANSWER VALUES (1, 1, 'First possible answer for question 1');
INSERT INTO ANSWER VALUES (2, 1, 'Second possible answer for question 1');
INSERT INTO ANSWER VALUES (3, 1, 'Third possible answer for question 1');
INSERT INTO ANSWER VALUES (4, 2, 'First possible answer for question 2');
INSERT INTO ANSWER VALUES (5, 2, 'Second possible answer for question 2');
INSERT INTO ANSWER VALUES (6, 3, 'First possible answer for question 3');
INSERT INTO ANSWER VALUES (7, 3, 'Second possible answer for question 3');
INSERT INTO ANSWER VALUES (8, 3, 'Third possible answer for question 3');
INSERT INTO ANSWER VALUES (9, 3, 'Fourth possible answer for question 3');

SELECT
  QUESTION.ID,
  COUNT(*) as NB_ANSWER
FROM QUESTION
INNER JOIN ANSWER ON QUESTION.ID = ANSWER.ID_QUESTION
GROUP BY QUESTION.ID
ORDER BY QUESTION.ID;

在此处查看:http://sqlfiddle.com/#!3/0025a/3/0

答案 1 :(得分:1)

要在SQL中解决此问题,您必须显式列出所有字段名称。假设在没有给出数据时您的字段值设置为NULL,SQL解决方案可能如下所示:

SELECT *, 
    ( answer1_a IS NOT NULL +
      answer1_b IS NOT NULL +
      answer1_c IS NOT NULL +
      answer1_d IS NOT NULL +
      answer1_e IS NOT NULL ) AS number_of_answers
FROM answers

一种可扩展的方法(当您更改表结构时自动增长,例如插入新的答案'f')将在PHP中进行此类计算:

<?php
$res = mysql_query("SELECT * FROM answers");
while ( $row = mysql_fetch_assoc($res) ) {
    $count = 0;
    foreach ( $row as $fieldname => $value ) {
        if ( strncmp($fieldname, 'answer1_', 8) === 0 &&
             $value !== NULL ) {
            $count++;
        }
    }
    $row['number_of_answers'] = $count;
    $resultset[] = $row;
}
print_r($resultset);

但是,PHP解决方案的缺点是您无法轻松使用HAVING语句中的WHERESELECT子句来查找(例如)所有可能有4个问题的问题答案。