I have two tables in my database:
(1) PHRASES:
t_phrase
========
I like
They prefer
...
Somebody else wants
and
(2) PLACES:
n_id t_place
==== =======
1 London
2 Paris
...
N New York
Table PHRASES
has at least as many rows as PLACES
. I need to join these two tables in such a way as to select all place
s with one phrase
for each of them - but phrases need to be randomly distributed across places. The overall places
table isn't too big: maybe, about 3-4 thousand rows, however there will be an additional WHERE
clause on it that will limit the output to about 200 places at most.
Ideally, I'd like this to be in one SQL statement, but so far I haven't been able to get my head around this. Therefore the second option is a stored function returning a row of (int, varchar, varchar)
. For this, I was thinking of something along the lines of:
- select all phrases in random order into an array of varchar
- loop over places taking one at a time and returning it along with the next phrase from the array
Somehow this seems to me very inefficient, but I can't come up with anything better.
Can you suggest any better idea? Or, even better, one statement SQL, maybe?
Thanks in advance.
EDIT: Please note that the phrases should NOT be repeated in the resultset. There are always at least as many phrases as there are places.