[英]MYSQL join random row from another table for each row
我有两张桌子:食物和配料(请参阅下面的图 1 )。
我希望将每种食物的成分随机化(可以是所有食物的重复成分)。 如何使用查询来检索价格呢? 谢谢
我尝试在 SQL 下面使用,但不是我想要的结果(请参阅图 2 ),因为如果使用sample SQL 1
,所有行的成分保证相同。 如果使用sample SQL 2
,价格也是随机的,与各自的成分不匹配。
/* sample SQL 1 */
select a.description, b.description, b.price
from Foods a
join (select a1.* from Ingredients a1 order by rand() limit 1) b
;
/* sample SQL 2 */
select a.description, (select a1.description from Ingredients a1 order by rand() limit 1) as description, (select a1.price from Ingredients a1 order by rand() limit 1) as price
from Foods a
如果您正在运行 MySQL 8.0,则可以为此使用row_number()
:
select *
from (
select
f.description as food,
i.description as ingredient,
i.price,
row_number() over(partition by f.id order by random()) rn
foods f
cross join ingredient i
) t
where rn = 1
这也适用于旧版本的 MySQL 数据库。
SELECT food, indeg, MAX(rn)
FROM (
SELECT x.*, @rn := @rn + 1 AS rn
FROM ( SELECT f.description AS food, i.description AS indeg
FROM Foods f
JOIN Ingredients i
ORDER BY RAND()
) x
JOIN (SELECT @rn := 0) r
) a
GROUP BY food
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.