MySQL next entry after certain condition
Well, MySQL isn't a specialty of mine, so there may be a better way of doing this. However, after checking to see how/if MySQL implemented various concepts (like SQL Server's ROW_NUMBER or LEAD functions), this appears to work.

This uses a trick, where the value of a variable is updated with each row, in sequence, and both the old and new values of the variable are included as columns. This lets us pick up the location from the previous row in the current row. (Note that I am not familiar enough with MySQL to know if this is a deliberate feature; in SQL Server, something similar works - but is not documented as a feature, and is generally thought of as something that could stop working with the next version.)

With that trick, we:


Limit our records to those that have one of the two locations we're interested in;
add the previous row's location to the current row; and
select the desired fields from the rows where the previous row's location is different from that of the current row.


Here's the code:

CREATE TABLE WhenWhatWhere (`when` datetime, `code` int, `location` char(1), CONSTRAINT PRIMARY KEY (`code`,`when`));

INSERT INTO WhenWhatWhere
VALUES ('2017-01-05 12:54', 102263, 'X')
      ,('2017-02-02 8:42', 102263, 'Y')
      ,('2017-03-02 12:04', 102263, 'Z')
      ,('2017-03-06 13:34', 102263, 'Y')
      ,('2017-03-07 7:57', 102263, 'Z')
      ,('2017-03-07 18:37', 102263, 'Y')
      ,('2017-03-09 17:47', 102263, 'Z')
      ,('2017-03-13 7:56', 102263, 'Y')
      ,('2017-03-21 11:44', 102263, 'Z')
      ,('2017-03-22 20:28', 102263, 'Y')
      ,('2017-03-24 13:07', 102263, 'X')
      ,('2017-03-25 14:01', 102263, 'Y')
      ,('2017-03-26 8:14', 102263, 'Z')
      ,('2017-03-27 9:52', 102263, 'Y')
      ,('2017-04-03 10:02', 102263, 'X')
;

SET @rownum = 0;
SET @loc1 = 'X';
SET @loc2 = 'Y';
SET @lastloc = '';

-- 
-- Select only the rows where the location changed from the previous row.
SELECT `when`, `code`, `location`
  FROM ( -- Add the location from the previous row; must be sorted to work
        SELECT `when`, `code`, @lastloc `lastloc`, (@lastloc := `location`) `location`
          FROM ( -- Select just the rows that deal with our two locations
                SELECT `when`, `code`, `location`
                  FROM WhenWhatWhere
                 WHERE `location` = @loc1 OR `location` = @loc2
                  -- add additional restrictions (like date range or specific code) here
               ) loc
         ORDER BY `when`
       ) comploc
 WHERE `lastloc` &lt;&gt; `location`
 ORDER BY `when`
;


It worked when I ran it at sqlfiddle.com.