用不同的字符串替换sql语句的输出

2eafrhcq  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(379)

我当前有一个填充表的输出。它给出的输出之一是学生表格中的一年。每当输出6作为年份时,我需要它返回l6,当输出7时,我需要u6。我试着吼叫:

"$stmt = $conn->prepare(
              "SELECT st.Name AS student, st.House AS house, T1.Name AS T1, T2.Name AS T2, T3.Name AS T3
              CASE
                WHEN st.Year = 6 THEN 'L6'
                WHEN st.Year = 7 THEN 'U6'
                ELSE st.Year
              END CASE as year
              From Students AS st INNER JOIN Student_Choices AS sc
              ON st.Username = sc.Username INNER JOIN Current_DB AS db
              ON sc.DB_year = db.DB
              INNER JOIN Choices AS c1
              ON sc.T1_Choice = c1.Choice_ID
              INNER JOIN Sports AS T1
              ON c1.Sport_ID = T1.Sport_ID
              INNER JOIN Choices AS c2
              ON sc.T2_Choice = c2.Choice_ID
              INNER JOIN Sports AS T2
              ON c2.Sport_ID = T2.Sport_ID
              INNER JOIN Choices AS c3
              ON sc.T3_Choice = c3.Choice_ID
              INNER JOIN Sports AS T3
              ON c3.Sport_ID = T3.Sport_ID
              ");

然后我得到一个错误:
errorsqlstate[42000]:语法错误或访问冲突:1064您的sql语法有错误;检查与您的mariadb服务器版本相对应的手册,以了解在第2行的“case when st.year=6 then'l6 when st.”附近使用的正确语法
任何解决方案都很好,谢谢。

zsohkypk

zsohkypk1#

case语句不能像那样独立存在,它们必须是主查询的一部分。把它们取下来试试

SELECT 
  st.Name AS student, 
  st.House AS house, 
  CASE 
    WHEN st.Year = 6 THEN 'L6' 
    WHEN st.Year = 7 THEN 'U6'
    ELSE st.Year 
  END CASE as year

…等等

ycl3bljg

ycl3bljg2#

答案如下:

SELECT st.Name AS student, st.House AS house,
              (CASE WHEN st.Year = 6 THEN 'L6' WHEN st.Year = 7 THEN 'U6' ELSE st.Year END) as year,
              T1.Name AS T1, T2.Name AS T2, T3.Name AS T3
              From Students AS st
              INNER JOIN Student_Choices AS sc
              ON st.Username = sc.Username INNER JOIN Current_DB AS db
              ON sc.DB_year = db.DB
              INNER JOIN Choices AS c1
              ON sc.T1_Choice = c1.Choice_ID
              INNER JOIN Sports AS T1
              ON c1.Sport_ID = T1.Sport_ID
              INNER JOIN Choices AS c2
              ON sc.T2_Choice = c2.Choice_ID
              INNER JOIN Sports AS T2
              ON c2.Sport_ID = T2.Sport_ID
              INNER JOIN Choices AS c3
              ON sc.T3_Choice = c3.Choice_ID
              INNER JOIN Sports AS T3
              ON c3.Sport_ID = T3.Sport_ID

案例需要放在括号内,选择时年份需要在其后

相关问题