php - MySQL limit characters in multi-select query -
sorry if there simple answer i'm new mysql , can't figure out how explain one:
i have number of queries select random words , concatenate them together. i'm trying limit query return results if under specific character limit. so, example, here's 1 query:
select concat((select word adjectives order rand() limit 1),' ', (select word2 verbs order rand() limit 1),' ', (select word nouns order rand() limit 1))
it returns result "adjective verb noun"
what want have query check if full concatenated result 30 characters or less; if is, return it, , if not, try again until 1 30 or fewer characters presented. thanks!
update: fantasy football team name generator, pulls "random" words various tables , strings them together. there literally millions of possible combinations.... if user specifies character limit, want sql re-try in background until finds , answer fits, present it. don't want user getting "please try again" kind of messages.
another approach let sql handle decision making , spit out string want. used sql procedure here.
delimiter $$ create or replace procedure `fetch_string`(in len int) begin declare temp varchar(100); declare isvalid boolean; declare maxlength int; declare minlength int; set maxlength = len; set isvalid = false; set minlength = (select min(length(n.word))+min(length(a.word))+min(length(v.word))+2 nouns n, adjectives a, verbs v); #that +2 in end compensating 2 spaces in between if maxlength < minlength set temp = ""; set isvalid = true; end if; while isvalid = false set temp = (select concat( (select word adjectives order rand() limit 1) ,' ', (select word verbs order rand() limit 1),' ', (select word nouns order rand() limit 1))); if length(temp) <= maxlength set isvalid = true; end if; end while; select temp; end$$ delimiter ;
this should it. can call , string matching requirement. no need process again.
is looking ?
edit: added input field length desired. , added condition check if given length greater smallest possible concat , if so, return empty string. avoid infinite loop in procedure.
Comments
Post a Comment