MYSQL enumeration: @rownum, odd and even entries

I asked a question about creating temporary / virtual identifiers for query results, mysql and php: temporary / virtual identifiers for query results?

I almost understood what I want with this link, http://craftycodeblog.com/2010/09/13/rownum-simulation-with-mysql/

I managed to list every line,

SELECT 
u.pg_id AS ID, 
u.pg_url AS URL,
u.pg_title AS Title,
u.pg_content_1 AS Content,
@rownum:=@rownum+1 AS rownum

FROM (
    SELECT pg_id, pg_url,pg_title,pg_content_1
    FROM root_pages

    WHERE root_pages.parent_id = '7'
    AND root_pages.pg_id != '7'
    AND root_pages.pg_cat_id = '2'
    AND root_pages.pg_hide != '1'

    ORDER BY pg_created DESC
) u,

(SELECT @rownum:=0) r

result

ID  URL     Title   Content     rownum
53  a       x       x           1
52  b       x       x           2
43  c       x       x           3
41  d       x       x           4

but how can I work on it a little further - I want to display odd or even entries only as the ones below - is this possible?

odd entries

ID  URL     Title   Content     rownum
53  a       x       x           1
43  c       x       x           3

even records

ID  URL     Title   Content     rownum
52  b       x       x           2
41  d       x       x           4

thank.

ps I do not quite understand the sql query, although I almost got the answer, for example, what do u and t mean?

+3
source share
1

"u" "t"?

, , .

, :

SELECT x.*
  FROM (SELECT u.pg_id AS ID, 
               u.pg_url AS URL,
               u.pg_title AS Title,
               u.pg_content_1 AS Content,
               @rownum := @rownum + 1 AS rownum
          FROM root_pages u
          JOIN (SELECT @rownum := 0) r
         WHERE u.parent_id = '7'
           AND u.pg_id != '7'
           AND u.pg_cat_id = '2'
           AND u.pg_hide != '1'
      ORDER BY u.pg_created DESC) x
WHERE x.rownum % 2 != 0

, :

SELECT x.*
  FROM (SELECT u.pg_id AS ID, 
               u.pg_url AS URL,
               u.pg_title AS Title,
               u.pg_content_1 AS Content,
               @rownum := @rownum + 1 AS rownum
          FROM root_pages u
          JOIN (SELECT @rownum := 0) r
         WHERE u.parent_id = '7'
           AND u.pg_id != '7'
           AND u.pg_cat_id = '2'
           AND u.pg_hide != '1'
      ORDER BY u.pg_created DESC) x
WHERE x.rownum % 2 = 0

% - MySQL - . , 1% 2 0,5, 2% 2 . WHERE .

+6

Source: https://habr.com/ru/post/1772384/


All Articles