[英]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. 我想从数据库中选择5个随机用户,并显示他们所有的食物偏爱。
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. 问题是:我不想限制返回的行,我只想限制不同的customer_id。 Buts since I have to select them randomly, I can't use math (like eg "WHERE customer_id < 6").
但是,由于我必须随机选择它们,因此无法使用数学运算(例如“ WHERE customer_id <6”)。 Is there a way to randomly select 5 customers and return all their food_preferences within the same query?
有没有一种方法可以随机选择5个客户,并在同一查询中返回他们所有的food_preferences?
First, never use commas in the FROM
clause. 首先, 切勿在
FROM
子句中使用逗号。 Always use explicit JOIN
syntax. 始终使用显式的
JOIN
语法。
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: 如果所有客户都有食物偏爱,只需将
limit
输入子查询即可:
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
: 如果不是所有客户都在
listing
而您只希望客户在listing
,则可以添加另一个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. 另外,建议使用现代的显式JOIN语法。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.