I have a SQLite "Details" table with the structure:
ID Name Category
---------------------
1 Matt 0
2 Shervin 0
3 Bob 0
4 Lee 0
5 Rick 0
6 Suraya 0
7 Susan 0
8 Adam 0
9 Jon 1
10 Lorna 1
... and so on .......
I want to select a row in random order, and then three names from three different rows (again, randomly). I would like all of this to be returned from a single SQLite statement. For instance.
ID Name Category Name1 Name2 Name 3
----------------------------------------
3 Bob 0 Matt Lee Susan
My attempt at this is described below, but it has two problems:
- The three additional names are not always always different - I cannot exclude the name that was previously selected because the b / c / d variables are not in scope except for the COALESCE native function.
- Since each nested selection uses the Random () function, it is not very efficient.
- ( SQLite)? / - , , , - .
:
SELECT a.Id,
a.Name,
a.Category,
COALESCE((SELECT b.Name
FROM Details b
WHERE b.Id NOT IN (a.Id)
AND b.Category IN (0)
ORDER BY Random()
LIMIT 1),'') as "Name1",
COALESCE((SELECT c.Name
FROM Details c
WHERE c.Id NOT IN (a.Id)
AND c.Category IN (0)
ORDER BY Random()
LIMIT 1),'') as "Name2",
COALESCE((SELECT d.Name
FROM Details d
WHERE d.Id NOT IN (a.Id)
AND d.Category IN (0)
ORDER BY Random()
LIMIT 1),'') as "Name3"
FROM Details a
AND a.Category IN (0)
ORDER BY Random()
LIMIT 1