简体   繁体   中英

MySQL match rows from 2 tables/query randomly

How can I match rows from 2 tables randomly?

Suppose I have

Users
-----
u1
u2
u3

And

Items
-----
i1
i2

I want to randomly match/join them like

Joined
------
u1   i2
u3   i1

Note that the rows in the resultant table is a "random" match. Also the size is the smaller of the 2 source tables users and items.

You want to join users to items, based on a relationship that doesn't exist (a "random" value, calculated on the fly).

In other words, for each user, you want to pick on random item.

Assuming there are no holes in your primary key sequence, you could write a query like this:

set @nb_items = select max(id) from items;

select users.id, items.id
from users
join items on items.id = floor(1 + rand() * @nb_items);

This query however will not prevent one item to be selected multiple times for different users.

So another way of approaching this problem is to materialize this "random" relationship. You could for example order both tables randomly, and join them using the row number as the key. Here is the query, with explicit table names for clarity:

set @i = 0;
set @j = 0;

select numbered_randomized_users.id, numbered_randomized_items.id
from (
  select id, @i := @i + 1 as row_number
  from (
     select id from users order by rand()
  ) as randomized_users
) as numbered_randomized_users
join (
  select id, @j := @j + 1 as row_number
  from (
    select id from items order by rand()
  ) as randomized_items
) as numbered_randomized_items using(row_number);

With this approach, the result set will only be the size of the smallest table, and some rows from the bigger table will be left out.

You can do this with a cartesian product and an ORDER BY RAND(). Be careful, using RAND() in an ORDER BY statement cause MySQL to do a full table scan so performance will be poor if you have many rows.

SELECT u.id, i.id FROM users as u, items as i
ORDER BY RAND() LIMIT {smallest table size}

Hope this help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM