0

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

例如,我有一张包含多项选择答案的问答表。有时一个问题有 3 个答案选项,有时有 4 个或 5 个。每个答案都在诸如answer1_aanswer1_banswer1_c等字段中——有没有办法确定这些字段中有多少有数据(对于给定的记录)?我需要它来确定要在 HTML 中显示多少个多项选择选项。

也许以某种方式使用mysql_num_fields ?

谢谢,杰夫

4

2 回答 2

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

于 2012-06-15T07:18:59.013 回答
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 解决方案的缺点是您不能轻易地在语句中使用HAVINGorWHERE子句SELECT来查找(例如)具有 4 个可能答案的所有问题。

于 2012-06-15T06:25:27.297 回答