简体   繁体   English

如何在sql查询中输入条件

[英]How to put condition in sql query

I want to show all scored records in score table and student name in student table if column "flag" equal "shown". 如果列“flag”等于“显示”,我想在学生表中显示得分表和学生姓名中的所有得分记录。 Else, if column "flag" in Score table equal "hidden" I will show all scored records with student name = "Student". 否则,如果Score表中的“flag”列等于“hidden”,我将显示所有带有student name =“Student”的得分记录。 Finally show all that in order of time. 最后按时间顺序显示所有内容。

Here is what I tried: 这是我尝试过的:

select s.student_name if h.flag = 'shown', select 'student' as s.student_name if h.flag = 'hidden',
   h.subject1_score,
   h.subject2_score,
   h.subject3_score,
   h.subject4_score,
   h.subject5_score,
   h.exam_date
from Score_Table h
join Student s on h.student_id = u.student_id
order by h.exam_date 

But that doesn't seem to work. 但这似乎不起作用。 What should I change? 我应该改变什么? Thank you! 谢谢!

Your IF syntax is off. 您的IF语法已关闭。 Read http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html 阅读http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html

select if(h.flag = 'shown',s.student_name,'student') student_name,
   h.subject1_score,
   h.subject2_score,
   h.subject3_score,
   h.subject4_score,
   h.subject5_score,
   h.exam_date
from Score_Table h
join Student s on h.student_id = s.student_id
order by h.exam_date 

The cASE i evolves as, cASE我演变为,

CASE WHEN h.flag = 'shown' 

It will check if the f.flag='shown' if true then it will select the s.studentName that is row value from table. 它将检查f.flag='shown'是否为true,然后它将从表中选择s.studentName作为行值。 And if the case is false then it will select the student as the StudentName . 如果案例是假的,那么它将选择student作为student StudentName

You can also use the case as, 您也可以将案例用作,

select 
     CASE WHEN h.flag = 'shown' THEN  s.student_name
     ELSE 'student' END AS StudentName,
   h.subject1_score,
   h.subject2_score,
   h.subject3_score,
   h.subject4_score,
   h.subject5_score,
   h.exam_date
from Score_Table h
join Student s on h.student_id = u.student_id
order by h.exam_date 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM