tags:

views:

104

answers:

4

I have a table with 9 rows.

$id=5
If i use SELECT * FROM tbl WHERE id>=$id i get the 5,6,7,8,9 rows. To this query I want to add the result of SELECT * FROM tbl WHERE id<$id so I will get the final 5,6,7,8,9,1,2,3,4 rows.

This is to avoid going two times in database then add the result set in php.

EDIT: Yes order is important. Thank you guys for the fast response. Thank you @knittl(Accepted answer) and @Swanand for the best answers.

A: 

UNION is your friend!

(SELECT *,1 as q FROM tbl WHERE id>=$id)
UNION
(SELECT *,2 as q FROM tbl WHERE id<$id)
ORDER BY q, id;
sfussenegger
union does not guarantee order
knittl
quoting mysql docs: »However, use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows.«
knittl
@knittl you're right. I didn't care too much about the order of results as the questions didn't say anything about it (the mentioned queries don't guarantee any order). I've now updated my answer to fulfill this additional requirement. For this very simple case, your answer still is more efficient though. In more complex scenarios, the constant (`q`) might come in handy (my hard-rocking amigo) though.
sfussenegger
A: 

try

$id=5;
SELECT * FROM tbl WHERE id>=$id
union
SELECT * FROM tbl WHERE id<$id ;
Yogesh
Well... yes but this is exactly the same as... SELECT * FROM tbl
Gimly
@Gimly - Not exactly. It is the same as `SELECT * FROM tbl WHERE id is not null`
Martin Smith
Or to take my pedantry one step further it is actually the same as `SELECT DISTINCT * FROM tbl WHERE id is not null`
Martin Smith
+6  A: 

you want all rows? if the order is what you are looking for, sort your result set:

SELECT * FROM tbl
ORDER BY id >= $id DESC, id ASC
knittl
Does this work in MySQL? Just tried with this: `order by id >= @id, id`, doesn't seem to. I am sure I am missing something.EDIT: I see, the `DESC` did the trick. +1 from me.
Swanand
it does, i just tested. is @id set? try using a literal value
knittl
+1  A: 

Try something like this...

SELECT *, (IF(id<5, true,false)) AS ltfive
FROM mytable
ORDER BY ltfive, id
Spudley
you are missing the FROM part
knittl
@knittle - oh yes. I'll fix that (not that it was a relevant part of the answer)
Spudley