数据库
首页 > 数据库> > 如何在MySQL v8中模拟LATERAL JOIN以执行每行的子查询或连接?

如何在MySQL v8中模拟LATERAL JOIN以执行每行的子查询或连接?

作者:互联网

我有两张桌子:

film  with primary key film_id
actor with primary key actor_id

我现在想填写一个表film_actor(film_id,actor_id),它将每部电影连接到250个随机演员.所以每部电影应该有250个不同的演员.

在PostgreSQL中,我会这样做:

insert into film_actor(film_id, actor_id)
select film_id, actor_id
from   film
cross join lateral
(
    select actor_id
    from   actor
    where  film_id is not null -- to force lateral behavior
    order  by random()
    limit  250
) as actor;

PostgreSQL小提琴可以在这里找到:https://dbfiddle.uk/?rdbms=postgres_10&fiddle=6dc21a3ce3404aaf3f4453e2ee4f863b.正如你所看到的,每部电影都有不同的演员.

我在MySQL v8中找不到对LATERAL JOIN的支持.你怎么能在MySQL v8中做这样的结构?

一个不工作的MySQL小提琴可以在这里找到:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6c1fb7df00cf8c73cbcca77752c9ef0d正如你所看到的,每部电影都有相同的演员.

解决方法:

这是一个相当低效的方法:

insert into film_actor (film_id, actor_id)
    select film_id, actor_id
    from (select f.film_id, a.actor_id,
                 row_number() over (partition by film_id order by rand()) as seeqnum
          from film f cross join
               actor a
         ) fa
    where seqnum <= 250;

还有一种使用递归CTE的方法,但我认为性能会更差.

标签:mysql,sql,mysql-8-0
来源: https://codeday.me/bug/20190622/1262343.html