-1

我有以下mysql查询:

SELECT 
  u.ID,
  u.StudentCode,
  c.classname,
  s.STUDENTNAME,
  u.UserCode,
  g.ForeName AS MessageSentBy,
  u.Message,
  u.ForTchrSname AS MessageSentTo,
  DATE_FORMAT(u.datetime, '%d-%m-%y') AS datesent,
  u.RecordStatus 
FROM
  tblupdates u,
  tblguardian g,
  tblstudent s,
  tblclass c 
WHERE u.UserCode = g.GuardianCode 
  AND u.StudentCode = s.STUDENTCODE 
  AND (
    YEAR(u.DateTime) = '2013' 
    AND MONTH(u.DateTime) = '09'
  ) 
  AND u.RecordStatus = 'N' 
  AND c.classcode = s.classcode 
ORDER BY u.datetime DESC 

此查询的结果如下所示: 在此处输入图像描述

现在在我的 2013 年和 09 月的 tblupdates 中,我有以下行: 在此处输入图像描述

现在在我上面的结果中,我正在获取数据,id=138但我想显示所有。不显示其他行的原因是(usercode-30000,admin)这些发生在tblteacher而不是tblguardian。所以现在我想要如果usercode来自tblguardian它显示监护人姓名,但如果它来自tblteacher它显示teachername但显示所有行。Tblteacher 和 tblupdates 可以分别由teachercode 和 usercode 加入。

我尝试了以下查询,但它没有返回任何行:

SELECT 
  u.ID,
  u.StudentCode,
  c.classname,
  s.STUDENTNAME,
  u.UserCode,
  IF(
    u.usercode NOT IN (g.guardiancode),
    t.teachername,
    g.ForeName
  ) AS MessageSentBy,
  u.Message,
  u.ForTchrSname AS MessageSentTo,
  DATE_FORMAT(u.datetime, '%d-%m-%y') AS datesent,
  u.RecordStatus 
FROM
  tblupdates u,
  tblguardian g,
  tblstudent s,
  tblclass c,
  tblteacher t 
WHERE u.UserCode = g.GuardianCode 
  AND u.StudentCode = s.STUDENTCODE 
  AND t.teachercode = u.usercode 
  AND (
    YEAR(u.DateTime) = '2013' 
    AND MONTH(u.DateTime) = '09'
  ) 
  AND u.RecordStatus = 'N' 
  AND c.classcode = s.classcode 
ORDER BY u.datetime DESC 

请帮帮我

4

1 回答 1

0

用 using 试试这个,CASE我已经使用 join 加入了你的表,LEFT所以可能有重复的我也使用GROUP BY过,u.id但对正确的列名有点困惑,请把正确的列放在 group by

SELECT 
  u.ID,
  u.StudentCode,
  c.classname,
  s.STUDENTNAME,
  u.UserCode,  
  (CASE 
  WHEN u.usercode = t.teachercode THEN t.teachername 
  WHEN u.usercode = g.guardiancode THEN g.ForeName 
  ELSE END ) AS MessageSentBy,
  u.Message,
  u.ForTchrSname AS MessageSentTo,
  DATE_FORMAT(u.datetime, '%d-%m-%y') AS datesent,
  u.RecordStatus 
FROM
  tblupdates u
  LEFT JOIN  tblguardian g ON (u.UserCode = g.GuardianCode )
  LEFT JOIN  tblstudent s ON (u.StudentCode = s.STUDENTCODE )
  LEFT JOIN  tblclass c ON (c.classcode = s.classcode )
  LEFT JOIN   tblteacher t  ON (t.teachercode = u.usercode)
WHERE   u.RecordStatus = 'N' 
 AND  (
    YEAR(u.DateTime) = '2013' 
    AND MONTH(u.DateTime) = '09'
  )  
GROUP BY u.id
ORDER BY u.datetime DESC 
于 2013-09-25T06:50:14.493 回答