jeudi 8 décembre 2022

In MySql, How to Associate Three Random Rows from One Table to Each Row of a Another Table

I have a table of Friends (Ann, Bob, Carl) and a table of Fruits (Apple, Banana, Cherry, Date, Fig, Grapefruit)

I need to create an intersection table (Friends X Fruit) that associates each Friend with 3 randomly selected fruits.

For example: Ann might be associated with Cherry, Date, Fig Bob might be associated with Apple, Fig, Banana Carl might be associated with Banana, Cherry, Date

I have developed a script that works well for only ONE friend (pasted below), but I am struggling to expand the script to handle all of the friends at once.

(If I remove the WHERE clause, then every friend gets assigned the same set of fruits, which doesn't meet my requirement).

Setup statements and current script pasted below.

Thank you for any guidance!

CREATE TABLE TempFriends ( FirstName VARCHAR(24) );
CREATE TABLE TempFruits ( FruitName VARCHAR(24) );
CREATE TABLE FriendsAndFruits( FirstName VARCHAR(24), FruitName VARCHAR(24) );
INSERT INTO TempFriends VALUES ('Ann'), ('Bob'), ('Carl');
INSERT INTO TempFruits VALUES ('Apple'), ('Banana'), ('Cherry'), ('Date'), ('Fig'), ('Grapefruit');

INSERT INTO FriendsAndFruits( FirstName, FruitName )
SELECT FirstName, FruitName
FROM TempFriends
INNER JOIN  ( SELECT FruitName FROM TempFruits ORDER BY RAND() LIMIT 3 ) RandomFruit
WHERE FirstName = 'Bob';



Aucun commentaire:

Enregistrer un commentaire