Here is my SQL query, it creates a single resulting row with two columns "below" and "above". They correspond to the primary keys ("id") of the rows in the Rankable table.
The purpose of the query is to select a random pair of Rankable rows that is not yet in the comparison table (which contains all the previous pairs).
However, I need this query to return two Rankables as strings, not just Rankable identifiers as fields on the same row.
This is the current request:
SELECT a.id AS lower, b.id AS higher
FROM Rankable a
INNER JOIN Rankable b on a.id < b.id
WHERE
a.category_id = ? AND b.category_id = ?
AND NOT EXISTS (
SELECT *
FROM Comparison c
WHERE c.lower_id in (a.id, b.id))
AND NOT EXISTS (
SELECT *
FROM Comparison c
WHERE c.higher_id IN (a.id, b.id))
ORDER BY a.id * rand()
LIMIT 1;
source
share