Select RAND() entry from GROUP BY with ORDER

Hello.

I want to select a random entry from GROUP BY query where entries with website_id = 0 should stay on bottom of the groups (should only be selected if there are no other items).

The table structure is:

name		website_id		content
n1			5				some content
n1			5				some content #2
n1			5				some content #3
n1			0				some stuff

I want to group_by query by name, where selected item would be randomly selected from those that have website_id = 5

SELECT * FROM table WHERE website_id = 5 OR website_id = 0 GROUP BY n1 ORDER BY RAND(), website_id ASC

the query should return:
some content
OR
some content #2
OR
some content #3

name		website_id		content
n1			0				some stuff #1
n1			0				some stuff #2
n2			3				blah..

the same query should return “some stuff #1” or “some stuff #2” row

So basically I have 2 problems… First one is to select random row from group, which I solved with the following query:

SELECT tmp.*
FROM blocks
LEFT JOIN (SELECT * FROM blocks ORDER BY RAND()) tmp ON (blocks.name = tmp.name)
GROUP BY tmp.name
ORDER BY blocks.name

But this query will rotate betwen website_id = 0 , which should be excluded if there is row with specified proper website_id

Any idea how it would be possible to solve this?

I know I could run 2 queries … to get website_id = 0 and website_id = id records separately but I’ve been wondering if its possible to write query to this at the same time.