简体   繁体   中英

MYSQL - ORDER BY & LIMIT: Different result when using variable or constant

Query 1:

set @userName = 'harry';

set @previousRegionId = (
        select Region as RegionID
        from log
        where User = @userName
        order by stamp desc
        limit 1);

select @previousRegionId;

Query 2:

set @previousRegionId = (
        select Region as RegionID
        from log
        where User = 'harry'
        order by stamp desc
        limit 1);

select @previousRegionId;

I expect the same result for both queries, but the result is different and it is reproduceable !

The log table contains same value in User column for all rows ('harry').

Changed the order by clause. Order by id works "better". Order by timestamp column is suspect ...

I am not 100% sure if this approach will work in all scenarios/aspects.

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