1

I have 1 table. I would like to create an small lottery game.

t1 have data as below.

+---------+------------------+-------------------+
| ID      | typeid           | createtime        |
+---------+------------------+-------------------+
| 1       | 1                | 123456            |
| 2       | 2                | 123123            |
| 3       | 1                | 12312312312       |
| 4       | 1                | 13123123          |
| 5       | 1                | 123dddddaasd123   |
+------------------------------------------------+

I would like to choose the winner when the typeid = 1.

My query like this (actually use query or fetch_all of fetch_first?)

$qsid = DB::fetch_all("SELECT * FROM ".DB::table('t1')." WHERE typeid = 1");

and I would like to use

array_rand to choose winner, so should be like array_rand(1,3,4,5);

then I can use the final result to set the winner. Or any suggestion for other better way?

Thank you.

2 Answers 2

3

Try This New One

SELECT `ID` 
FROM `t1` 
WHERE `ID` IN (
               SELECT `ID` 
               FROM `t1` 
               WHERE `typeid` = 1)
ORDER BY RAND()
LIMIT 1
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. but my DB:: function was not allow me for SELECT in a SELECT for query safety issue, anyway, the ORDER BY RAND() is what I need, thank you !
try this $select = $db->select()->from(array('t' => 't1'),array('ID')) ->where("WHERE ID IN (SELECT ID FROM t1 WHERE typeid = 1)") ->order('ORDER BY RAND()') ->limit('LIMIT 1');
actually we can do it multiple ways but we need to keep in mind about performance inner query is less optmised rather that single query
ya i know but i only just simply guide you that your query will be like this ,then you have to modify your query depend on your requirement.i just guide as like your Question. so don't forget to accept it / up vote it (click on the little greyed check mark / Up arrow beside this answer). Thanks
2

We can do it in various way, let's do it as below.

1st way: let's do it on mysql level

select ID from t1 where typeid =1 order by RAND() limit 1;

above query will select random row of mysql where typeid is 1.

2nd way:let's do it on coding level

we need to select ID from t1 where typeid =1 and keep it in any array and then select random element from the array

int array[]={1,3,4,5}
int finalResultId = array[java.util.new Random().nextInt(array.length)]

I hope it will help you out. Thanks

1 Comment

I think the order by RAND() limit 1; is already enough for me, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.