0

Here is a sample table.

ColZero | ColOne | RoColTwo
--------+--------+--------
   1    | one    | tag1
   2    | two    | tag1
   3    | three  | tag2
   4    | four   | tag2
   5    | five   | tag3

I have the following query.

SELECT `ColOne` FROM `Table` WHERE `ColTwo` = ? ORDER BY rand() LIMIT 1;

I'd like to select multiple rows, using multiple values of RowTwo in a single query but each row still has to be random.

This involves merging a variable number of instances of this query into a new, single query.

How can this be done in one query? (I am trying to make this as quick as possible, so getting it all done in one request, as opposed to 10-30 requests is a big plus.)

1
  • Are you confusing the terms "Row" and "Col"? Commented Oct 26, 2016 at 23:39

2 Answers 2

2

Probably the most efficient way to do what you want is to use variables:

SELECT t.*
FROM (SELECT t.*,
             (@rn := if(@r = RowTwo, @rn + 1,
                        if(@r := RowTow, 1, 1)
                       )
             ) as rn
      FROM `Table` t CROSS JOIN
           (SELECDT @r := '', @rn := 0) params
      WHERE `RowTwo` IN (?, ?, ?)
      ORDER BY RowTwo, rand()
     ) t
WHERE rn = 1;

If you don't want to use dynamic SQL and you want to support an indefinite number of values, you might consider:

WHERE FIND_IN_SET(RowTwo, ?) > 0

In any case, naming columns ROW causes (for me at least) cognitive dissonance.

Sign up to request clarification or add additional context in comments.

2 Comments

Ty! Oops, fixed the naming. I'm struggling to understand some of this. What goes in place of params?
I'm not sure what you mean. The ? are the values that you want to check RowTwo for. You can leave out that where clause to get a random row for each value.
1

You could use union using different value for RowTo

SELECT `RowOne` FROM `Table` WHERE `RowTwo` = ? ORDER BY rand() LIMIT 1

union 

SELECT `RowOne` FROM `Table` WHERE `RowTwo` = ? ORDER BY rand() LIMIT 1

union 

SELECT `RowOne` FROM `Table` WHERE `RowTwo` = ? ORDER BY rand() LIMIT 1

union 

SELECT `RowOne` FROM `Table` WHERE `RowTwo` = ? ORDER BY rand() LIMIT 1 ;

2 Comments

Ty! The only problem is that forces the selection of a fixed number of rows.
yIn someway yes .. you can only change change the limit and the number of union ..

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.