我打算运行一个查询,在提供admission_code
时提供最新的欠款,但是存在一些逻辑错误:
SELECT *
FROM fees_invoice_information AS fii
WHERE fii.admission_code = 12111
此SQL返回:
当我想从以下查询中获取最新记录时
SELECT
MAX(fii.id),fii.*,
sep.registration_code,
sep.admission_code,
fii.arrears,
sep.is_enabled
FROM
fees_invoice_information AS fii
JOIN
std_education_profile AS sep ON fii.admission_code = sep.admission_code
WHERE
fii.`admission_code` = 12111
我明白了:
其中"欠款"列不是' 0'
答案 0 :(得分:1)
将MAX
条件移至WHERE
子句中的子查询:
SELECT fii.*,
sep.registration_code,
sep.admission_code,
sep.is_enabled
FROM fees_invoice_information AS fii
INNER JOIN std_education_profile AS sep
ON fii.admission_code = sep.admission_code
WHERE fii.admission_code = 12111 AND
fii.id = (SELECT MAX(id) FROM fees_invoice_information)
或者你可以使用LIMIT 1
技巧:
SELECT fii.*,
sep.registration_code,
sep.admission_code,
sep.is_enabled
FROM fees_invoice_information AS fii
INNER JOIN std_education_profile AS sep
ON fii.admission_code = sep.admission_code
WHERE fii.admission_code = 12111
ORDER BY fii.id DESC
LIMIT 1
注意:这假定根据最大ID仅返回单个记录是合乎逻辑的。如果连接不是一对一,那么您可能希望返回记录的组或一组记录的聚合。