简体   繁体   中英

How can I select 5 random rows from one table and list the rows from a second?

Ok, I have 2 tables. On called items , where all the data is stored(id, name, description, ect.) and a second table called featured where a list of featured items is stored(id, itemid)

What I would like to do is select 5 random rows from the featured table and list that match itemid in the items table. The items table is somewhat big, 300,000 rows or so, and the featured currently has 106.

Secondary question: would it be better if I just add a column to the items table that sets a bool if its featured or not?

SELECT  *
FROM    featured f
JOIN    items i
ON      i.id = f.itemid
ORDER BY
        RAND()
LIMIT   5

This query though might take long on a large dataset.

I personally think it'd be better to use another column rather than another table because both tables have the same superkey. It sounds like a JOIN will work just fine for you.

SELECT * FROM featured f JOIN items ON (f.id = itemid) ORDER BY RAND() LIMIT 5;

I think the most efficient way is:

select *
from (select f.*
      from featured f
      order by rand()
      limit 5
     ) f join 
     items i
     on i.id = f.itemId;

In your case, the sort on 106 versus 5 rows is probably immaterial in terms of performance. But if the featured list grows, then it might make a difference.

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