简体   繁体   中英

Two SQL queries returning odd results

I am going to run a query which gives latest arrears when provided with admission_code , but there is some logical error:

SELECT * 
FROM fees_invoice_information AS fii
WHERE fii.admission_code = 12111

This SQL returns:

enter image description here

While when I want to get latest record from following query

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

I get:

enter image description here

In which "arrears" column is not '0'

Move the MAX criteria to a subquery in the WHERE clause:

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)

Or you could use a LIMIT 1 trick:

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

Note: This assumes that it makes logical sense to return only a single record based on the max ID. If the join isn't one to one then you might want to return a group of records, or an aggregate of a group of records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM