I have a form to edit mysql table columns. There are links that I can click onto and load Previous, Next, First or Last row. I can order the columns (max. four columns to be ordered). So when I press Prev. or Next, the columns have to be ordered first and then I can get the result. I use mysql View for this. It is important to know that columns are text, but id is number. I usually ord开发者_开发百科er by first text columns and then by id.
And here is my query that worked to me for single column order.
Previous:
SELECT x.*
FROM test_view x, test_view y
WHERE y.`id` = 13
AND ( x.`cat` < y.`cat` OR ( x.`cat` = y.`cat` AND x.`id` < y.`id`))
ORDER BY x.`cat`, x.`id` DESC
LIMIT 0,1
Next:
SELECT x.*
FROM test_view x, test_view y
WHERE y.`id` = 13
AND (x.`cat` > y.`cat` OR (x.`cat` = y.`cat` AND x.`id` > y.`id`))
ORDER BY x.`cat`, x.`id` ASC
LIMIT 0,1
I tried to expand this to find multiple columns as this:
SELECT x . *
FROM ukazka_view x, ukazka_view y
WHERE y.`id` =1
AND (
x.`cat` < y.`cat`
OR (
x.`cat` = y.`cat`
AND x.`id` < y.`id`
)
)
AND (
x.`typ` < y.`typ`
OR (
x.`typ` = y.`typ`
AND x.`id` < y.`id`
)
)
AND (
x.`diff` < y.`diff`
OR (
x.`diff` = y.`diff`
AND x.`id` < y.`id`
)
)
ORDER BY x.`cat` DESC , x.`typ` DESC , x.`diff` DESC , x.`id` DESC
LIMIT 0 , 1
But this has no results.
Edited:
I tried to write a query for case that actual row id is 1.
SELECT x.* FROM ukazka_view x INNER JOIN ukazka_view y ON
( x.`cat` < y.`cat` OR
( x.`cat` = y.`cat` AND x.`id` < y.`id`) OR
( x.`cat` = y.`cat` AND y.`id` = 1 AND x.`id` > y.`id`))
AND
( x.typ
< y.typ
OR
( x.typ
= y.typ
AND x.id
< y.id
) OR
( x.typ
= y.typ
AND y.id
= 1 AND x.id
> y.id
))
AND
( x.diff
< y.diff
OR
( x.diff
= y.diff
AND x.id
< y.id
) OR
( x.diff
= y.diff
AND y.id
= 1 AND x.id
> y.id
))
WHERE y.id
= 1
ORDER BY x.cat
DESC, x.typ
DESC, x.diff
DESC, x.id
DESC LIMIT 0,1
This looks for previous row. Behavior is a little bit strange but works. So when I go to last value, I got id=1. Then When I press Previous (this query) it gets to id=82, when I press again Previous id=81 and so on till I got id=2. I cannot get to id=1 only when I press/select Last.
SELECT x.*
FROM ukazka_view x
INNER JOIN ukazka_view y
ON (x.cat < y.cat OR (x.cat = y.cat AND x.id < y.id))
AND (x.typ < y.typ OR (x.typ = y.typ AND x.id < y.id))
AND (x.diff < y.diff OR (x.diff = y.diff AND x.id < y.id))
WHERE y.id = 1
ORDER BY x.cat DESC , x.typ DESC , x.diff DESC , x.id DESC
LIMIT 1 OFFSET 0
The problem I see with this query is that an id cannot be smaller than 1.
So x.id < y.id
will always be false.
This leaves only
....
ON (x.cat < y.cat)
AND (x.typ < y.typ)
AND (x.diff < y.diff)
As a join criterion.
精彩评论