简体   繁体   中英

Limit random returned id's, but with unknown row count per id

I want to select 5 random users out of my database and show all their food preferences.

Currently I have these tables:

CUSTOMERS
customer_id email 

FOOD_PREFERENCE
food_id food_name allergic_info

LISTING
customer_id food_id

My query has to be something similar to this:

SELECT c.email, f.food_name, f.allergic_info
FROM customers c, food_preference f, listing l
WHERE l.customer_id=c.customer_id AND f.food_id=l.food_id
ORDER BY rand(c.customer_id) LIMIT 10

The problem is: I don't want to limit the rows that are returned, I just want to limit the different customer_id's. Buts since I have to select them randomly, I can't use math (like eg "WHERE customer_id < 6"). Is there a way to randomly select 5 customers and return all their food_preferences within the same query?

First, never use commas in the FROM clause. Always use explicit JOIN syntax.

So, your query should be:

SELECT c.email, f.food_name, f.allergic_info
FROM listing l JOIN
     customers c  
     ON l.customer_id = c.customer_id JOIN
     food_preference f
     ON f.food_id = l.food_id
ORDER BY rand(c.customer_id)  -- I don't know why you are providing a see here
LIMIT 10;

If all customers have food preferences, just put the limit in a subquery:

SELECT c.email, f.food_name, f.allergic_info
FROM listing l JOIN
     (SELECT c.*
      FROM customers c  
      ORDER BY rand()
      LIMIT 5
     ) c
     ON l.customer_id = c.customer_id JOIN
     food_preference f
     ON f.food_id = l.food_id;

If not all customers are in listing and you only want customers in listing , then you can add another join :

SELECT c.email, f.food_name, f.allergic_info
FROM listing l JOIN
     customers c
     ON l.customer_id = c.customer_id JOIN
     food_preference f
     ON f.food_id = l.food_id JOIN
     (SELECT customer_id
      FROM (SELECT DISTINCT customer_id FROM LISTING) lc
      ORDER BY rand()
      LIMIT 5
     ) lc
     ON l.customer_id = lc.customer_id

You can limit the customer in subquery and then do the JOINs.

Also, it's recommended to use the modern explicit JOIN syntax.

select c.email,
    f.food_name,
    f.allergic_info
from listing l
join (
    select *
    from customers
    order by rand() limit 10
    ) c on l.customer_id = c.customer_id
join food_preference f on f.food_id = l.food_id;

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