我构建了以下查询:
SELECT
p.id,
p.tag_id,
p.title,
p.created_at,
@indexer := @indexer + 1 AS indexer
FROM
`posts` AS p
LEFT JOIN
`votes` AS v
ON p.id = v.votable_id
AND v.votable_type = "Post"
AND v.deleted_at IS NULL
JOIN
(SELECT @indexer := 0) AS i
WHERE
p.deleted_at IS NULL
GROUP BY
p.id
我得到的结果是:
+----+--------+------------------------------------+---------------------+---------+
| id | tag_id | title | created_at | indexer |
+----+--------+------------------------------------+---------------------+---------+
| 2 | 2 | PostPostPost | 2014-10-23 23:53:15 | 248 |
| 3 | 3 | Title | 2014-10-23 23:56:13 | 6 |
| 4 | 2 | GIFGIFIGIIF | 2014-10-23 23:59:03 | 1316 |
| 5 | 2 | GIFGIFIGIIF | 2014-10-23 23:59:03 | 1317 |
| 6 | 4 | My new avatar | 2014-10-26 22:22:30 | 1318 |
| 7 | 5 | Hi, haiii, oh Hey ! | 2014-10-26 22:38:10 | 1 |
| 8 | 6 | Mclaren testing stealth technology | 2014-10-26 22:44:15 | 5 |
| 9 | 7 | Just random thoughts while pooping | 2014-10-26 22:50:03 | 2 |
+----+--------+------------------------------------+---------------------+---------+
然而,我期待着这一点:
+----+--------+------------------------------------+---------------------+---------+
| id | tag_id | title | created_at | indexer |
+----+--------+------------------------------------+---------------------+---------+
| 2 | 2 | PostPostPost | 2014-10-23 23:53:15 | 1 |
| 3 | 3 | Title | 2014-10-23 23:56:13 | 2 |
| 4 | 2 | GIFGIFIGIIF | 2014-10-23 23:59:03 | 3 |
| 5 | 2 | GIFGIFIGIIF | 2014-10-23 23:59:03 | 4 |
| 6 | 4 | My new avatar | 2014-10-26 22:22:30 | 5 |
| 7 | 5 | Hi, haiii, oh Hey ! | 2014-10-26 22:38:10 | 6 |
| 8 | 6 | Mclaren testing stealth technology | 2014-10-26 22:44:15 | 7 |
| 9 | 7 | Just random thoughts while pooping | 2014-10-26 22:50:03 | 8 |
+----+--------+------------------------------------+---------------------+---------+
提示:问题在于indexer
字段。它是在添加GROUP BY
语句后发生的。
我尝试移动JOIN (SELECT @indexer := 0) AS i
,将其更改为额外的选择,但没有更改。无论如何,指数都搞砸了。
如何解决这个问题,以便索引正确?
这个问题背后的原因是什么?
答案 0 :(得分:0)
我自己找到答案,不得不将查询分成多个子查询。
SELECT
mq.*,
@indexer := @indexer + 1 AS indexer
FROM
(
SELECT
p.id,
p.tag_id,
p.title,
p.created_at
FROM
`posts` AS p
LEFT JOIN
`votes` AS v
ON p.id = v.votable_id
AND v.votable_type = "Post"
AND v.deleted_at IS NULL
WHERE
p.deleted_at IS NULL
GROUP BY
p.id
) AS mq
JOIN
(SELECT @indexer := 0) AS i
显然,这导致查询的大量访问行(按照EXPLAIN
),但设法通过额外的索引来修复它。可以在此处找到该问题的完整答案:Calculating row indices with subquery having joins, results in A*B examined rows