是否可以在查询中获取表的列名?我正在使用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);
答案 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;