简体   繁体   中英

SQL Query, get random row from a filtered selection

I use the following SQL query to get two random rows.

entry.sql
SELECT id, userID, img, points, votes 
FROM entry
WHERE rotation = 1
ORDER BY RAND()
LIMIT 2

Now I would like to filter the possible rows. I do this here by rotation but I want more.

I have a second and a third table which look like this:

users.sql    
ID | username

voted.sql
ID | userID | entryID | timestamp

I only want to get rows which the user hasn´t already voted on. So we should get all entryIDs for the user from voted.sql and make sure that the query above doesn´t pick them, how can I do this ?

Or would you save the data, in a different way, to make the already voted check easier ?

Use a join or subquery to do this, like:

SELECT id, user.userID, entry.img, entry.points, entry.votes
FROM entry
WHERE userID NOT IN (SELECT DISTINCT userID 
                     FROM voted
                     WHERE userID = entry.userID);

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