简体   繁体   中英

Fetching only first row from joined table

I have a table called 'tests' where i have tests stored. I have another table called 'test_changes' where i store change log of the tests table. Each time when a test record is changed the test_changes table will get a new row with current timestamp. If a 'tests' record have not been edited before there will be no record for it in the test_change table.

Now am in need of querying the database for all tests and its first ever change record.

select * 
from tests 
left join (select MIN(created_on) as created_on, test_id 
           from `test_changes` 
           group by test_id) as tc on tests.id = tc.test_id

But it is not fetching MIN values for all the 'tests'... for some test records it is fetching MAX value which is strange. I googled but couldnot able to find a solution which suits my need. can someone tell me what am i missing in the above query? why it is giving MAX value on some records? 'created_on' field is UNIXTIMESTAMP data

Is this what you need?

SELECT
    MIN(created_on) AS created_on,
    test_id
FROM
    test_changes
GROUP BY
    test_id
    

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