tags:

views:

27

answers:

4

Hi all.

I want to display two records.

For eg select * FROM users WHERE user_id = 5.

Now i want another row randomly selected from users table but with user_id != 5

Is it possible to do in a single query. I tried using union all but i dnt get two distinct rows.

Thanks

A: 

Try this

SELECT * FROM users WHERE user_id = 5 || user_id != 5 ORDER BY RAND() LIMIT 2
madsleejensen
Won't work: Will not necessarily give user ID 5 as the first result
Pekka
Ah yes your right :)
madsleejensen
+5  A: 

This works fine for me. The first result is always the record with ID 5, the second row is a random one. Note that if no record with the ID 5 exists, both rows will be random.

SELECT * FROM users ORDER BY (user_id = 5) DESC, RAND() LIMIT 0,2 
Pekka
This is correct, an no <code>UNION</code> +1
Joony
THanks pekka. I tried your query. It works great. +1. What if i have a condition. Can i use it in there. say eg SELECT * FROM users ORDER BY (now() BETWEEN start_date and end_date) DESC, RAND() LIMIT 0,2 ??
noobcode
@noobcode sure, depending on what you want to do. The random row won't be covered by the condition this way
Pekka
@pekka Simply entering the condition did not work.So i put a subquery. This is how the query looks."" SELECT * FROM users ORDER BY (user_id = (select user_id FROM users WHERE the_condition)) DESC, RAND() LIMIT 0,2 "" This works perfect. Thanks a lot. Appreciate.
noobcode
A: 

Union should do the trick. You probably forgot LIMIT.

(SELECT * FROM users WHERE user_id = 5 LIMIT 1)
UNION
(SELECT * FROM users WHERE user_id != 5 LIMIT 1)
elusive
A: 

Try this:

SELECT * FROM users WHERE user_id=5
union all (
  SELECT * FROM  users WHERE user_id!=5
  ORDER BY RAND() LIMIT 0,1)
Dewfy