I have two tables like these:
CREATE TABLE people (
id INT NOT NULL,
PRIMARY KEY (id)
)
CREATE TABLE pairs (
person_a_id INT,
person_b_id INT,
FOREIGN KEY (person_a_id) REFERENCES people(id),
FOREIGN KEY (person_b_id) REFERENCES people(id)
)
I want to select pairs of people at random from the people table, and after selecting them I add the randomly select pair to the pairs table. person_a_id always refers to the person with the lower id of the pair (since the order of the pair is not relevant).
The thing is that I never want to select the same pair twice, so I need to check the pairs table before I return my randomly selected pair.
Is it possible to do this using just a single SQL query in a reasonably efficient and elegant manner?
(I’m doing this using the Java Persistence API, but hopefully I’ll be able to translate any answers into JPA code)
Limit 1returns just one pair if you are “drawing lots” one at a time. Otherwise, up the limit to however many pairs you need.The above query assumes that you can get
and that the pairing
2 - 7is valid since it doesn’t exist, even if 2 is featured again. If you only want a person to feature inonly onepair ever, thenIf
multiple pairsare to be generated in one single query, AND the destination table is still empty, you could use this single query. Take note thatLIMIT 6returns only 3 pairs.