按学生姓名获取列名称

时间:2015-11-05 12:09:48

标签: php mysql pdo

是否可以在查询中获取表的列名?我正在使用PDO

 stu_name      maths   science   music  art  

 John          done      done      -    done   
 Max             -       done      -    done   
 Peter          -        done      -     -   

E.g。如何获得John未完成(-)的主题? music应该是结果。

这就是我现在所处的位置。我不知道怎么做。

$sql = "SELECT * FROM coll_student WHERE stu_name = :name AND ?? = '-' LIMIT 1";
$stat = $connect->prepare($sql);
$stat->execute(array(':name'=>"John"));
$output = $stat->fetchAll(PDO::FETCH_COLUMN);

1 个答案:

答案 0 :(得分:7)

你可以这样做:

SELECT
  GROUP_concat(COALESCE(CASE WHEN maths   = '-' THEN 'maths'   END, ''), 
               COALESCE(CASE WHEN science = '-' THEN 'science' END, ''), 
               COALESCE(CASE WHEN art     = '-' THEN 'art'     END, ''), 
               COALESCE(CASE WHEN music   = '-' THEN 'music'   END, '')) AS SubjectsNotDone
FROM coll_student 
WHERE stu_name = 'John'
AND ((maths    = '-') OR
      (science = '-') OR
      (art     = '-') OR
      ( music  = '-')) ;

这会给你:

| SubjectsNotDone |
|-----------------|
|           music |

但是,您的表格不是normalized。通过创建新表Subjects

,您可以使其更简单,更轻松,性能更高
  • SubjectId
  • SubjectName

然后表coll_student将是这样的:

  • stu_name
  • SubjectId - Foreign key到主题表:

    constraint FK_SubjectId foreign key (SubjectId) references Subjects(SubjectId)
    
  • Status:bit或int作为完成与否的标志(或其他状态,如果有)。

然后你的查询会更简单,就像这样:

SELECT subjectname
FROM coll_student AS c
INNER JOIN Subjects AS s ON c.SubjectID = s.SubjectId
WHERE c.name = 'John' AND c.Status = 0;