我问了一个关于为查询结果创建临时/虚拟ID的问题, mysql & php: temporary/ virtual ids for query results?
我几乎得到了这个链接, http://craftycodeblog.com/2010/09/13/rownum-simulation-with-mysql/
我已设法枚举每一行,
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
结果,
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
但我怎样才能进一步处理它 - 我想只显示奇数或偶数记录,如下所示 - 是否可能?
奇数记录,
ID URL Title Content rownum
53 a x x 1
43 c x x 3
甚至记录,
ID URL Title Content rownum
52 b x x 2
41 d x x 4
谢谢。
P.S。我实际上并不太了解sql查询,即使我几乎得到了答案,例如,'u'和't'是什么意思?
答案 0 :(得分:6)
'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子句中使用它来过滤显示的行。