我有以下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
{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
请帮帮我
答案 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}}