dsdsdsdsd Posted February 5, 2011 Share Posted February 5, 2011 I have my_table: col_1 | col_2 ------------- aaa | mmm bbb | nnn ccc | ooo ddd | ppp eee | qqq fff | rrr I have php: $max_return = 4 ; $priority_val = 'ddd' I want rows: - if ddd is found it should be first else ignore it - all the rest should be randomly picked/ordered - no more than max rows returned any thoughts? thanks, Shannon Quote Link to comment https://forums.phpfreaks.com/topic/226802-select-query-with-random-order-limit-but-with-specific-1st-item-if-found/ Share on other sites More sharing options...
sunfighter Posted February 5, 2011 Share Posted February 5, 2011 you can do a WHERE col_1 ddd You have do the rand yourself because I dont think you can do it in a query. you can check for ddd before the query final query you can LIMIT the search to 4. find it all here http://www.w3schools.com/sql/default.asp Quote Link to comment https://forums.phpfreaks.com/topic/226802-select-query-with-random-order-limit-but-with-specific-1st-item-if-found/#findComment-1170405 Share on other sites More sharing options...
dsdsdsdsd Posted February 6, 2011 Author Share Posted February 6, 2011 this works, though messy: ( select * from my_table where col_A = 'something' and approved = 'true' ) union ( select * from my_table where col_A != 'something' and approved = 'true' ORDER BY RAND() limit 0,5 ) the only problem is that the max number, 5, should be conditioned upon whether first select succeeded or not ... but not a big deal. if first select succeeded, then max = max-1 // max = 4 else max = max // max = 5 Quote Link to comment https://forums.phpfreaks.com/topic/226802-select-query-with-random-order-limit-but-with-specific-1st-item-if-found/#findComment-1170598 Share on other sites More sharing options...
fenway Posted February 13, 2011 Share Posted February 13, 2011 Use: ORDER BY col_A = 'ddd', RAND() Quote Link to comment https://forums.phpfreaks.com/topic/226802-select-query-with-random-order-limit-but-with-specific-1st-item-if-found/#findComment-1173582 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.