如果学生有很多记录,下面的查询工作正常,但如果学生只有一条记录,那么除非我删除HAVING
条款,否则查询不会返回任何内容。有什么理由或任何解决方案?
由于
注意:我要做的是返回给定学生的最新签证和护照详细信息,但问题是,我无法使用ORDER BY
,因为<没有订购强>签证和护照。最新记录并不意味着它真的是最新的!
SELECT
person._______......,
student._______......,
passport.passport_expiry_date,
visa.visa_expiry_date,
FROM person
INNER JOIN student ON student.personid = person.id
LEFT JOIN visa ON visa.personid = person.id
LEFT JOIN passport ON passport.personid = person.id
WHERE
student.id = '776'
HAVING
MAX(visa.visa_expiry_date) AND
MAX(passport.passport_expiry_date)
LIMIT 1
答案 0 :(得分:1)
尝试更改此部分:
WHERE
student.id = '776'
HAVING
MAX(visa.visa_expiry_date) AND
MAX(passport.passport_expiry_date)
到此:
WHERE
student.id = '776'
AND visa.visa_expiry_date = (SELECT MAX(visa_expiry_date) from visa WHERE visa.personid = student.personid GROUP BY visa.personid)
AND passport.passport_expiry_date = SELECT MAX(passport_expiry_date) from passport WHERE passport.personid = student.personid GROUP BY passport.personid)