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 e.g. "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