根据条件从多个表中获取fieldname

时间:2013-09-25 06:32:21

标签: mysql asp.net sql database join

我有以下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 

此查询的结果如下所示: enter image description here

现在在我的2013年和09年的tblupdates中,我有以下几行: enter image description here

现在,在我的上述结果中,我正在获取id=138的数据,但我想显示所有内容。不显示其他行的原因是(usercode-30000,admin)这些行发生在tblteacher而不是tblguardian {1}}。所以现在我希望如果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 

请帮帮我

1 个答案:

答案 0 :(得分:0)

使用CASE尝试使用LEFT并使用GROUP BY加入我已经加入了表格,因此我可以使用u.id重复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 但是有点混淆了列名请将右列放在

组中
{{1}}